How do I configure a Doctrine2 entity which extends PersistentObject within Symfony2 project?

前端 未结 1 1103
我在风中等你
我在风中等你 2021-01-06 18:13

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 p

相关标签:
1条回答
  • 2021-01-06 19:04

    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 
    
    0 讨论(0)
提交回复
热议问题