1

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

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

如何使用 Propel2 实现这一目标?我可以createdBy在控制器中设置,但这很丑:(

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

4

1 回答 1

0

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

想法:模型将为Event Dispatcher. 在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 \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"]

Config 基于symfony 框架。实际实现:

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

于 2016-05-20T06:13:12.297 回答