G
G
grabbee2016-02-26 15:37:31
symfony
grabbee, 2016-02-26 15:37:31

How to set an Entity property in Symfony2 that is the result of a service?

What do you do if you need to set some property of the model as the result of another service. For example, there is a resource that can be accessed by presenting an access code (token). The code is generated by the service based on [param + secret + expire] => hash
The model data is returned to the client as JSON data with a list of resources along with keys to each resource. What is the right way to implement this in Symfony?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grabbee, 2016-02-27
@grabbee

Added an event listener as a service through tags to inject my configured service into the listener according to the description for the
The necessary annotation is described there [/** @Entity @EntityListeners({"UserListener"}) */] was a piece of code, but the dependency injection implementation was not described:

<?php
// User.php

/** @Entity @EntityListeners({"UserListener"}) */
class User
{
    // ....
}

// UserListener.php
class UserListener
{
    public function __construct(MyService $service)  <<<
    {
        $this->service = $service;
    }

    public function preUpdate(User $user, PreUpdateEventArgs $event)
    {
        $this->service->doSomething($user);
    }
}

// register a entity listener.
$listener = $container->get('user_listener');
$em->getConfiguration()->getEntityListenerResolver()->register($listener);

Total:
1. Specify an annotation referring to the event listener class
2. Create a listener class and describe the logic necessary to set entity properties using external services
3. Inject these services as listener arguments in the class constructor
4. Using the name tag: doctrine.orm.entity_listener register listener/service
Shoot me((

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question