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

属性2,createdBy字段

  •  1
  • po_taka  · 技术社区  · 10 年前

    假设我有“问题”模型。 每个问题都由用户(当前用户)创建。 如何“自动”更新 createdBy current.user

    在Doctrine2中,我应该有依赖于 security.context . 事件将订阅 preSave() 背景 $question->setCreatedBy( $context->getToken()->getUser());

    如何使用Propel2实现这一点?我可以设置 创建者 在控制器中,但这很难看:(

    我可以写自定义 behavior ,但如何访问 安全性上下文 从行为上看?

    1 回复  |  直到 9 年前
        1
  •  0
  •   po_taka    9 年前

    大约半年后,我找到了有效的解决方案:)

    想法:模型将有setter注入 Event Dispatcher 在…上 pre-save 模型将触发事件(验证/用户注入等)。这样我需要ED来保存。我可以在没有注入ED的情况下从DB中选择对象。 依赖关系管理器将管理“存储库”。Repo将能够在模型上注入所有必需的依赖项,然后调用save。 $depepndanciesManager->getModelRepo->save($model) . 女巫会做: $model->setEventDispacher($this->getEventDispacher); $model->save();

    模型示例:

    class Lyric extends BaseLyric
    {
        private $eventDispacher;
    
        public function preSave(ConnectionInterface $con = null)
        {
            if (!$this->validate()) {
                // throw exception
            }
    
            $this->notifyPreSave($this);
            return parent::preSave($con);
        }
    
        private function getEventDispacher()
        {
            if ($this->eventDispacher === null) {
                throw new \Exception('eventDispacher not set');
            }
            return $this->eventDispacher;
        }
        public function setEventDispacher(EventDispacher $eventDispacher)
        {
            $this->eventDispacher = $eventDispacher;
        }
        private function notifyPreSave(Lyric $lyric)
        {
            $event = new LyricEvent($lyric);
            $this->getEventDispacher()->dispatch('tekstove.lyric.save', $event);
        }
    }
    

    存储库示例:

    class LyricRepository
    {
        private $eventDispacher;
    
        public function __construct(EventDispacher $eventDispacher)
        {
            $this->eventDispacher = $eventDispacher;
        }
    
        public function save(Lyric $lyric)
        {
            $lyric->setEventDispacher($this->eventDispacher);
            $lyric->save();
        }
    }
    

    控制器使用示例:

    public function postAction(Request $request)
    {
        $repo = $this->get('tekstove.lyric.repository');
        $lyric = new \Tekstove\ApiBundle\Model\Lyric();
        try {
            $repo->save($lyric);
            // return ....
        } catch (Exception $e) {
            // ...
        }
    }
    

    示例配置:

    tekstove.lyric.repository:
        class: Tekstove\ApiBundle\Model\Lyric\LyricRepository
        arguments: ["@tekstove.event_dispacher"]
    

    配置基于 symfony framework . 实际实施:

    链接可能不起作用,项目正在积极开发中!

    推荐文章