简体   繁体   中英

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. Users are fetched through a DI service which connects to a web service. 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.

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?

I would definately use the postLoad event. And as a first step you can inject a user from the webservice in there. 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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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