douzhi1937 2012-11-26 21:49
浏览 53
已采纳

在实体中创建一个方法,在调用它时进行延迟加载

I work with Redis loaded as a service to inject followers to a entity. So i've a entity like User that has a method like getFollowers. I don't want to mix service with entities, so I make a listener that subscribe to postLoad events in Doctrine.

The question is how call the service only when I call the getFollowers method.

My code...

EventListener:

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));

    }

}

User entity:

public function setFollowers(Array $followers) {
    $this->followers = $followers
}

My problem is that on every load of class user, the RedisService is called and loaded, and I'd like to call the service ONLY on $user->getFollowers

  • 写回答

2条回答 默认 最新

  • doumei9832 2012-12-12 08:58
    关注

    Finally I get the answer...

    In my listener postLoad I assign a closure to property of object:

    $socialGraph = $this->socialGraph;
    $getFollowers = function() use ($socialGraph, $user) {
        return $socialGraph->getFollowers($user->getId());
    };
    
    $user->setFans($getFollowers);
    

    Now, in my object it's possible to call a method into a property with:

    public function getFans()
    {
        return call_user_func($this->fans);
    
     // another way
        return $this->fans->__invoke();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分