我有一个描述我的应用程序中模型的文档,我想在加载文档后更改字段值,我发现这样做的方法是使用事件侦听器。我在我的 config/services.yml 中添加了一个新的侦听器(postLoad 侦听器),我不知道如何在发送文档之前获取文档并对其进行更改。
帮助将不胜感激。 :)
这是我添加到config/service.yml(在服务下)的内容
core.listener:
class: MatanCoreBundleEventListenerDocumentListener
tags:
- { name: doctrine_mongodb.odm.event_listener, event: postLoad }
文档侦听器.php
namespace MatanCoreBundleEventListener;
use MatanCoreBundleDocumentApp;
class DocumentListener
{
public function postLoad()
{
//I Want to change it here
}
}
解决方案:
应指定应在服务定义中调用的侦听器方法:
- { name: doctrine_mongodb.odm.event_listener, event: postLoad, method: onPostLoad }
现在,您可以将刚刚从 EventArgs 加载的文档传递给 onPostLoad
方法。
检查它是否与要更改的模型匹配,然后执行更改。
use DoctrineODMMongoDBEventLifecycleEventArgs;
use AcmeYourDocumentMyDocument;
public function onPostLoad(LifecycleEventArgs $eventArgs)
{
$document = $eventArgs->getDocument();
if !($document instanceof MyDocument) {
return;
}
// ... your code here
// $document->setLoaded(new Date('now'));
}