假设我有模型“问题”。每个问题都是由用户(当前用户)创建的。如何“自动”将createdBy更新为current.user
在Doctrine2中,我应该有依赖于security.context的事件侦听器。事件将订阅preSave(),设置$question->setCreatedBy( $context->getToken()->getUser());
如何用Propel2实现这一点?我可以在控制器中设置createdBy,但这很难看:
我可以编写自定义行为,但是如何从行为中访问security.context呢?
发布于 2016-05-20 06:13:12
~半年后,我找到了解决办法:)
想法:模型将为Event Dispatcher注入setter。在pre-save上,模型会触发事件(验证/用户注入等)。这样我就需要艾德来拯救。我可以在没有注入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框架的。真正的执行:
链接可能不起作用,项目正在积极开发!
https://stackoverflow.com/questions/31903364
复制相似问题