我使用作为服务加载的 Redis 将关注者注入(inject)实体。所以我有一个像 User 这样的实体,它有一个像 getFollowers 这样的方法。我不想将服务与实体混合,所以我创建了一个订阅 Doctrine 中的 postLoad 事件的监听器。
问题是只有当我调用 getFollowers 方法时如何调用服务。
我的代码...
事件监听器:
public function postLoad(LifecycleEventArgs $eventArgs)
{
$redisService = get the service loaded with DIC in constructor.
if ($eventArgs->getEntity() instanceof User) {
$user = $eventArgs->getEntity();
$user->setFollowers($redisService->getFollowers($user));
}
}
用户实体:
public function setFollowers(Array $followers) {
$this->followers = $followers
}
我的问题是,每次加载用户类时,都会调用和加载 RedisService,我只想在 $user->getFollowers 上调用该服务
最佳答案
终于找到答案了...
在我的监听器 postLoad 中,我为对象的属性分配了一个闭包:
$socialGraph = $this->socialGraph;
$getFollowers = function() use ($socialGraph, $user) {
return $socialGraph->getFollowers($user->getId());
};
$user->setFans($getFollowers);
现在,在我的对象中,可以通过以下方式将方法调用到属性中:
public function getFans()
{
return call_user_func($this->fans);
// another way
return $this->fans->__invoke();
}
关于php - 在实体中创建一个方法,在调用它时执行延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573744/