Symfony2 - extending entities, abstract entity

后端 未结 2 1163
暖寄归人
暖寄归人 2021-01-07 04:11

I have 2 entities with the same fields - parent, children, order. Actually it is a mechanism and this 3 fields not applicable to content of this entity - like name, title, c

2条回答
  •  半阙折子戏
    2021-01-07 04:45

    i would make an abstract class with doctrines @MappedSuperClass annotation and shared fields and the entities extend them

    here is an example with a shared created_at field

    namespace Your\CoreBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\ORM\Mapping\MappedSuperclass;
    
    
    
    /**
     * Abstract base class to be extended by my entity classes with same fields
     *
     * @MappedSuperclass
     */
    abstract class AbstractEntity {
    
        /**
         * @var integer
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;
    
        /**
         * @ORM\Column(name="created_at", type="datetime")
         */
        private $createdAt;
    
    
        /**
         * Get id
         * @return integer
         */
        public function getId() {
            return $this->id;
        }
    
        /**
         * Get createdAt
         * @return \DateTime
         */
        public function getCreatedAt() {
            return $this->createdAt;
        }
    
        /**
         * Set createdAt
         *
         * @param \DateTime $createdAt
         *
         * @return AbstractEntity
         */
        public function setCreatedAt($createdAt)
        {
            $this->createdAt = $createdAt;
    
            return $this;
        }
    
    } 
    

    your entities both extend this class like:

    class YourEntityClass extends AbstractEntity
    {
    

    in YourEntityClass the $id property must be "protected"

提交回复
热议问题