大约半年后,我找到了有效的解决方案:)
想法:模型将有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
.
实际实施:
链接可能不起作用,项目正在积极开发中!