Is it possible to create a mapping from one entity A to entity B but instead just store an array within entity A which contains only the ID's of related entity B.
class A
{
/**
* #var int
*/
protected $id;
/**
* #var int[] One to many relationship which only has the ID's of class B
*/
private $bIds;
...
}
class B
{
/**
* #var int
*/
protected $id;
/**
* #var A Many to one relationship
*/
private $a;
}
Related
I have some common fields in almost all tables. So I created an AbstractEntity class where I can add fields that are in common.
/**
* #MappedSuperclass
*/
abstract class AbstractEntity
{
/**
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", options={"unsigned"=true})
*/
protected int $id;
/**
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
protected string $createdAt;
public function getId(): int
{
return $this->id;
}
public function createdAt(): string
{
return $this->createdAt;
}
public function setShopLocale(string $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
Now, I extend Abstractclass in other EntityClass
class Random extends AbstractEntity
{
}
I am getting following error message when I try to insert record.
Class "App\Entity\Admin\Random" sub class of "App\Entity\Admin\AbstractEntity" is not a valid entity or mapped super class.
// in some file
/**
* #typedef myspace
* #property {Object} models
* #property {Object} services
*/
// in other files
/** #typedef myspace.models.ModelA */
class ModelA { ... }
/** #typedef myspace.models.ModelB */
class ModelB { ... }
/** #typedef myspace.services.ServiceA */
class ServiceA { ... }
How to define classes with JSDoc if I want to make them as members of the namespaces myspace.models and myspace.services?
You need using #namespace and #memberOf, I believe
Can a class be put into a member group like a function? For example,
/** Some module.
*
* #defgroup Group
* #{
*/
/** #name Same utility
*
*/
/** #{*/
/** Class A.
*
*/
class A
{
};
/** Function.
*
*/
void f();
/** #}*/ // end Same utility
/** Class B.
*
*/
class B
{
};
/** #}*/ // end Group
The above code will put f() into a custom section called "Same utility", but the document for class A is still in the section "class" with class B. So is there a way to group the class A into a member group as well?
I'm trying create something using ZF2 and Doctrine 2. But I'm kind lost about what I want to achieve.
First I now that using $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); inside controller it will work.
But what I want it's something more elaborated, like this:
class BaseModel extends Doctrine\ORM\EntityManager
{
public function save()
{
$em->persist($this);
$em->flush();
}
}
/**
* #ORM\Entity
*/
class Customer extends BaseModel
{
// getters setters
}
class IndexController
{
public function indexAction()
{
$customer = new Customer();
$customer->setName('asd');
$customer->save();
Customer::findAll();
}
}
I have started this:
namespace Ws\Model;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
class BaseModel implements ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait;
public function write() {
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
return $em->getRepository(__CLASS__);
}
}
But without success.
I understand that this is more than one question, but is it possible help me here even passing some links that could help me in this journey?
Thank you.
Did you have a look at the Zend\ServiceManager\ServiceLocatorAwareTrait implemntation ? It just give you the getter and setter, but of course, if you never set it, you will never get it. So $this->getServiceLocator() will always return null.
You'd better use dependency injection (never inject service locator but the needed services) or maybe, as pointed by #Cerad, use Doctrine the way it was designed.
You're in luck. Just created that myself to use in my own vendor package.
You're code is messy though, I'm going to assume that the "Model" your refer to is the Entity and not a combination of Entity and Repository.
However, to the code!
Make special note of the namespaces and organize folder structure and file names accordingly!
File: repoName/src/Entity/AbstractEntity.php
<?php
namespace Company\Core;
use Doctrine\ORM\Mapping as ORM;
use Company\Core\Listener\ServiceLocatorAwareEntity;
/**
* Class AbstractEntity
* #package Company\Core\Entity
*
* #ORM\MappedSuperclass
* #ORM\HasLifecycleCallbacks
*/
abstract class AbstractEntity extends ServiceLocatorAwareEntity
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
* #return AbstractEntity
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
}
File: repoName/src/Service/AbstractEntityService.php
<?php
namespace Company\Core\Service;
use Doctrine\ORM\EntityManager;
use Company\Core\Interfaces\EntityServiceInterface;
abstract class AbstractEntityService implements EntityServiceInterface
{
/**
* #var EntityManager
*/
protected $entityManager;
/**
* AbstractEntityService constructor.
* #param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* #return EntityManager
*/
public function getEntityManager()
{
return $this->entityManager;
}
/**
* #return \Doctrine\ORM\EntityRepository
*/
public function getEntityRepository()
{
return $this->getEntityManager()->getRepository(__CLASS__);
}
//Feel free to add more functions here that you want all of your Entities to have
}
File: repoName/src/Interfaces/EntityServiceInterface.php (note, plural "interfaces" folder, as "interface" is protected name in PHP)
<?php
namespace Company\Core\Interfaces;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Repository\RepositoryFactory;
interface EntityServiceInterface
{
/**
* #return EntityManager
*/
public function getEntityManager();
/**
* #return RepositoryFactory
*/
public function getEntityRepository();
//Feel free to add more functions here
}
File: repoName/src/Listener/ServiceLocatorAwareEntity.php
<?php
namespace Company\Core\Listener;
use Zend\Di\ServiceLocator;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ServiceLocatorAwareEntity implements ServiceLocatorAwareInterface
{
protected $sm;
/**
* Set the service locator
*
* #param ServiceLocatorInterface $sm
*
* #return void
*/
public function setServiceLocator(ServiceLocatorInterface $sm)
{
$this->sm = $sm;
}
/**
* Get the service locator
*
* #return ServiceLocator ServiceLocator instance
*/
public function getServiceLocator()
{
return $this->sm;
}
}
In the Module.php file add following onBootstrap() function
public function onBootstrap(MvcEvent $e)
{
$sm = $e->getApplication()->getServiceManager();
/** #var EntityManager $em */
$em = $sm->get('doctrine.entitymanager.orm_default');
/** #var \Doctrine\Common\EventManager $dem */
$dem = $em->getEventManager();
/**
* Binds adding EventListener "ServiceManagerListener" to the Doctrine Event PostLoad
*/
$dem->addEventListener([Events::postLoad], new ServiceManagerListener($sm));
}
Because of this setup, make sure to had the #ORM\HasLifecycleCallbacks Doctrine Annotation to the Entity class. The above function triggers the adding of the ServiceManagerListener, which in turn triggers the remainder.
Now all that remains is using it in your own modules (repeat endlessly if needed :) ).
Here we go back to the application itself.
Make sure you do the below for each of your entities and controllers and you should be fine.
Create the following:
<?php
namespace Application\Service;
use Company\Core\Service\AbstractEntityService;
class IndexControllerService extends AbstractEntityService
{
//Yes really, this class is empty. Extends an Abstract class which may not be directly instantiated.
}
Create a factory for you IndexController
<?php
namespace Application\Factory;
use Application\Controller\IndexController;
use Application\Service\IndexControllerService;
use Doctrine\ORM\EntityManager;
use Zend\Mvc\Controller\ControllerManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\ServiceManager;
class IndexControllerFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface|ControllerManager $serviceLocator
* #return IndexController
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** #var ServiceManager $serviceManager */
$serviceManager = $serviceLocator->getServiceLocator();
/** #var EntityManager $entityManager */
$entityManager = $serviceManager->get('doctrine.entitymanager.orm_default');
/** #var IndexControllerService $entityService */
$entityService = new IndexControllerService($entityManager);
/** #var IndexController $controller */
$controller = new IndexController($entityService);
return $controller;
}
}
Make sure that your IndexController extends the AbstractActionController
<?php
namespace Application\Controller;
use Company\Core\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
public function indexAction()
{
return [];
}
}
And make sure that you've registered this configuration in the config files using the following:
'controllers' => [
'factories' => [
IndexController::class => IndexControllerFactory::class,
],
],
'service_manager' => [
'invokables' => [
IndexControllerService::class => IndexControllerService::class,
],
],
There ya go, should be all set.
I have 2 entities - a User and a Tag.
This is my user:
<?php
namespace Project\Model;
/**
* #Entity
* #Table(name="users")
* #InheritanceType("JOINED")
* #DiscriminatorColumn(name="discr", type="string")
* #DiscriminatorMap({"user" = "User", "client" = "Client", "staff" = "Staff"})
**/
class User implements \JsonSerializable {
/** #Id #Column(type="integer") #GeneratedValue **/
protected $id;
/** #Column(type="string", name="first_name") **/
protected $firstName;
/**
* #ManyToMany(targetEntity="Project\Model\Tag", inversedBy="users")
* #JoinTable(name="user_tags")
**/
protected $tags;
/**
* Construct a new user.
*/
public function __construct() {
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
// Getters
public function getId() {
return $this->id;
}
public function getFirstName() {
return $this->firstName;
}
public function getTags() {
return $this->tags;
}
// Setters
public function setFirstName($firstName) {
$this->firstName = $firstName;
}
/**
* Add a tag to a user.
* #param Tag
*/
public function addTag(Tag $tag) {
$tag->addUser($this);
$this->tags[] = $tag;
}
}
This is my Tag:
<?php
namespace Project\Model;
/**
* #Entity
* #Table(name="tags")
**/
class Tag implements \JsonSerializable {
/** #Id #Column(type="integer") #GeneratedValue **/
protected $id;
/** #Column(type="string") **/
protected $tag;
/**
* #ManyToMany(targetEntity="Project\Model\User", mappedBy="tags")
*/
protected $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
// Getters
public function getId() {
return $this->id;
}
public function getTag() {
return $this->tag;
}
// Setters
public function setTag($tag) {
$this->tag = $tag;
}
public function addUser(User $user) {
$this->users[] = $user;
}
}
If I create a new Tag, a new User, add the Tag to the User, then call the getTag() method, it returns nothing -- can anybody help me out where I am going wrong?
$tag = new Tag();
$tag->setTag('Foo');
$entityManager->persist($tag);
$user = new User();
$user->addTag($tag);
$entityManager->persist($user);
$entityManger->flush();
var_dump($user->getTags());
I think the problem might come from your ManyToMany relation. You use
#ManyToMany(targetEntity="Tag", inversedBy="users")
whereas you should have something like (assuming you are using Symfony 2 of course) :
#ManyToMany(targetEntity="AppBundle\Entity\Tag")
Also, you use a inversedBybut no mappedBy, so your mapping is invalid.
And this last one is more of a detail, but name a property "tag" inside a Tag class is not the cleanest. Maybe change it to "name".
In your Tag class, you reference the User class using:
/**
* #ManyToMany(targetEntity="Bix\Model\User", mappedBy="tags")
*/
Should "Bix" be "Project"? Unless this was a typo in your question, that woud cause issues.
One side should "own" the association and be responsible for setting the inverse association when it is added.
<?php
// Assuming that the User is the "owning side".
class User {
// Mappings as you have them, minus the "Bix" namespace thing.
public function getTags()
{
return $this->tags;
}
public function addTag(Tag $tag)
{
$tag->addUser($this);
$this->tags->add($tag);
}
public function removeTag(Tag $tag)
{
$tag->removeUser($this);
$this->tags->removeElement($tag);
}
}
class Tag {
// Mappings as you have them, minus the "Bix" namespace thing.
public function getUsers()
{
return $this->users;
}
public function addUser(User $user)
{
$this->users->add($user);
}
public function removeUser(User $user)
{
$this->users->removeElement($user);
}
}