Symfony2 - extending entities, abstract entity

后端 未结 2 1144
暖寄归人
暖寄归人 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:31

    I had that issue some time ago. I also wanted to have nice abstraction for entities (or value objects, whatever) just to be a little lazy. But It is not the good way IMHO.

    What if name from one entity has to have other length than the other? What if you want to add new field, add it to one entity, and some time later you wanted it in the other entity, but you forget to move it to abstraction?

    I think entity is such autonomic thing that it is pointless and confusing to move some part of it to the abstraction.

    Remember about KISS principle.

    0 讨论(0)
  • 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"

    0 讨论(0)
提交回复
热议问题