How do I configure a Doctrine2 entity which extend

2020-03-05 08:20发布

I would like to be able to use the PersistentObject described here http://www.doctrine-project.org/blog/a-doctrine-orm-odm-base-class.html during development of a Symfony2 project, to avoid creating and deleting getters and setters endlessly whilst the database and entity design are in flux.

Where in a Symfony2 project does one 'configure' the ObjectManager, as suggested in the brief documentation (code quote below)? Should it be in the controller, and if so, what would it look like?

 $entityManager = EntityManager::create(...);
 PersistentObject::setObjectManager($entityManager);

I cannot find any working examples (although I did find this parallels example for the Zend2 framework on stackoverflow: Using PersistentObject from Doctrine in Zend Framework

Thanks for your time!

1条回答
Summer. ? 凉城
2楼-- · 2020-03-05 08:30

The PersistentObject is an object which you don't manually have to persist. It thereby provides magic getters and setters using php's __call() method.

You simply extend the Object in your entity class and use it inside your controller. without the need to generate getters and setters.

example entity

<?php
namespace Vendor\YourBundle\YourEntity;

use Doctrine\Common\Persistence\PersistentObject; 
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Mapping as ORM;

class YourEntity extends PersistentObject
{

   // i added the constructor in order to save the setObjectManager() 
   // call in the the controller

   public function __construct(ObjectManager $om)
   {
       $this->setObjectManager($om);
   }

   /** 
    * @ORM\Id  
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    */
   protected $id;

   /**
    * @ORM\Column(type="string", length=100)
    */
   protected $name;

   // ... more properties

}

example controller action

class YourController extends Controller
{
    public function yourAction($name)
    {
        $em = $this->get('doctrine')->getManager('default');

        $entity = new YourEntity($em);   // __construct calls setObjectManager($em)

        $entity->setName($name);         // magic setter is used here

        // ... no need for $em->persist($entity);

        $em->flush();                    // $entity is being persisted.
    }

    // ...

You get the doctrine entity manager inside a symfony controller using one of ...

 $em = $this->get('doctrine')->getManager();          // gets default manager
 $em = $this->get('doctrine')->getManager('default'); // same as above
 $em = $this->getDoctrine()->getManager();            // using alias 
查看更多
登录 后发表回答