代码之家  ›  专栏  ›  技术社区  ›  Arcades

Symfony生命周期回调注释的继承

  •  0
  • Arcades  · 技术社区  · 7 年前

    我使用symfony4,生命周期回调有问题。我有两个班,一个模特儿和一个这个模特儿。我希望模型的每个子级都有相同的preposist回调,但是回调不会被触发。这是正常的还是我做错了什么?

    <?php
    // src/Models/QuestionModel.php
    
    namespace App\Models;
    
    use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @ODM\MappedSuperclass
     * @ODM\HasLifecycleCallbacks
     */
    class QuestionModel
    {
      /**
       * @ODM\Id(strategy="AUTO")
       */
      protected $id;
    
      /**
       * @ODM\Field(type="date")
       */
      protected $createdAt;
    
      /**
       * @ODM\PrePersist
       */
      public function setCreatedAtValue() {
        $this->createdAt = new \DateTime();
      }
    

    孩子:

    <?php
    // src/Document/CDN/Question.php
    
    namespace App\Document\CDN;
    
    use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
    use App\Models\QuestionModel;
    
    /**
     * @ODM\Document(collection="CDNQuestion")
     * @ODM\HasLifecycleCallbacks
     */
    class Question extends QuestionModel
    {
    }
    

    谢谢

    0 回复  |  直到 7 年前
        1
  •  0
  •   Kamil Ścisłowski    7 年前

    trait TimestampableTrait
    {
        /**
         * @var \DateTime
         *
         * @ORM\Column(type="datetime", nullable=false)
         */
        protected $createdAt;
    
        /**
         * @var \DateTime
         *
         * @ORM\Column(type="datetime", nullable=true)
         */
        protected $updatedAt;
    
        /**
         * @ORM\PrePersist
         */
        public function updateCreatedAt()
        {
            $this->createdAt = new \DateTime();
        }
    
        /**
         * @ORM\PreUpdate
         */
        public function preUpdate()
        {
            $this->updatedAt = new \DateTime();
        }
    
        /**
         * @return \DateTime|null
         */
        public function getUpdatedAt()
        {
            return $this->updatedAt;
        }
    
        /**
         * @return \DateTime
         */
        public function getCreatedAt()
        {
            return $this->createdAt;
        }
    
        /**
         * @return string
         */
        public function getCreatedAtFormatted()
        {
            if ($this->createdAt instanceof \DateTime) {
                return $this->createdAt->format('d/m/Y h:i:s A');
            }
    
            return '';
        }
    }