〜半年后,我找到了可行的解决方案:)
想法:模型将为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 框架。实际实现:
链接可能无效,项目正在积极开发中!