简体   繁体   English

Symfony2和Doctrine-通过服务延迟加载实体的属性

[英]Symfony2 & Doctrine - Lazy load an entity's property through a service

I'm wondering whether it's possible to make a custom Doctrine proxy or similar which would allow me to lazy load an Entity's property from a service. 我想知道是否有可能创建自定义的教义代理或类似的代理,以使我可以从服务中延迟加载实体的属性。

EXAMPLE: 例:

class Article {
  ...
  /** @ORM\Column(type=integer) **/
  protected $userId;

  /** @var /MyUser  **/
  protected $user;
}

$user property is not handled by doctrine. $ user属性不由原则处理。 Users are fetched through a DI service which connects to a web service. 通过连接到Web服务的DI服务获取用户。 What I would like to do is hook into doctrine so when $article->user is used the object is lazy loaded using the custom defined DI service. 我想做的就是融入理论,因此当使用$article->user时,将使用自定义的DI服务来延迟加载对象。

Any idea whether that is possible? 知道这是否可能吗?

If lazy loading is not possible, would it be possible to hook into the postLoad event and load the user object using the predefined service? 如果无法进行延迟加载,是否可以挂接到postLoad事件中,并使用预定义的服务加载用户对象?

I would definately use the postLoad event. 我一定会使用postLoad事件。 And as a first step you can inject a user from the webservice in there. 作为第一步,您可以从那里的Web服务注入用户。 As a second step you could easily inject a Proxy in the postLoad event and this proxy would then be responsible to load the actual data lazy. 第二步,您可以轻松地在postLoad事件中注入一个代理,然后该代理将负责延迟加载实际数据。

EXAMPLE: First you need to configure your listener: 示例:首先,您需要配置您的监听器:

services:
    my.listener:
        class: Acme\MyBundle\EventListener\UserInjecter
        arguments: ["@my_api_service"]
        tags:
            - { name: doctrine.event_listener, event: postLoad }

Then you need to implement the listener: 然后,您需要实现侦听器:

namespace Acme\MyBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\UserBundle\Entity\User;

class UserInjecter
{
    protected $myApiService;    

    public function __construct($myApiService){
       $this->myApiService = $myApiService;
    }

    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();


 $entityManager = $args->getEntityManager();


    if ($entity instanceof User) {
        $entity->apiuser = $this->myApiService->loadUserData($entity->getIdentifier());
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM