Propel2, createdBy field



假设我有一个模型"Question"。每个问题都由用户(当前用户)创建。如何"自动"更新createdBycurrent.user

在Doctrine2中,我应该有依赖于security.context的事件侦听器。事件将订阅preSave(),设置$question->setCreatedBy( $context->getToken()->getUser());

如何实现这与Propel2 ?我可以在控制器中设置createdBy,但这是丑陋的:(

我可以编写自定义行为,但如何从行为访问security.context ?

半年后我找到了可行的解决方案:)

想法:模型将为Event Dispatcher注入setter。在pre-save模型将触发事件(验证/用户注入等)。这样我就需要ED来保存。我可以选择对象从数据库没有注入ED。依赖管理器将管理"存储库"。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 TekstoveApiBundleModelLyric();
    try {
        $repo->save($lyric);
        // return ....
    } catch (Exception $e) {
        // ...
    }
}

示例配置:

tekstove.lyric.repository:
    class: TekstoveApiBundleModelLyricLyricRepository
    arguments: ["@tekstove.event_dispacher"]

Config基于symfony框架。真正的实现:

  • config -在这里输入链接描述
  • 模型-在这里输入链接描述
  • 控制器-在这里输入链接描述
  • "Repo"的工厂输入链接描述在这里

链接可能无法工作,项目正在积极开发中!

最新更新