Symfony 2.0 getting service inside entity

Nie mogę znaleźć odpowiedzi. Mam wzór do naśladowania w mojej aplikacji. Użytkownik może mieć rolę, ale ta rola musi być zapisana w bazie danych.

Ale wtedy użytkownik musi mieć domyślną rolę dodaną z bazy danych. Więc stworzyłem serwis:

<?php

namespace Alef\UserBundle\Service;

use Alef\UserBundle\Entity\Role;

/**
 * Description of RoleService
 *
 * @author oracle
 */
class RoleService {

    const ENTITY_NAME = 'AlefUserBundle:Role';

    private $em;

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

    public function findAll()
    {
        return $this->em->getRepository(self::ENTITY_NAME)->findAll();
    }

    public function create(User $user)
    {
        // possibly validation here

        $this->em->persist($user);
        $this->em->flush($user);
    }

    public function addRole($name, $role) {
        if (($newrole = findRoleByRole($role)) != null)
            return $newrole;
        if (($newrole = findRoleByName($name)) != null)
            return $newrole;

        //there is no existing role
        $newrole = new Role();
        $newrole->setName($name);
        $newrole->setRole($role);

        $em->persist($newrole);
        $em->flush();

        return $newrole;
    }

    public function getRoleByName($name) {
        return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('name' => $name));
    }

    public function getRoleByRole($role) {
        return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('role' => $role));
    }

}

Moje services.yml to:

alef.role_service:
    class: Alef\UserBundle\Service\RoleService
    arguments: [%doctrine.orm.entity_manager%]

A teraz chcę go użyć w dwóch miejscach: UserController i User podmiot. Jak mogę je wprowadzić do środka? Co do kontrolera to chyba muszę:

$this->get('alef.role_service');

Ale jak uzyskać obsługę wewnątrz / align = "left" /

Author: Kaminari, 2012-04-26

2 answers

To bardzo częste pytanie. Podmioty powinny wiedzieć tylko o innych podmiotach, a nie o menedżerze podmiotu lub innych usługach wysokiego poziomu. Przejście na ten sposób rozwoju może być wyzwaniem, ale zazwyczaj jest tego warte.

To, co chcesz zrobić, to załadować rolę podczas ładowania użytkownika. Zazwyczaj skończysz z UserProvider, który robi tego rodzaju rzeczy. Czytałeś sekcje o ochronie? To powinno być twoje punkt wyjścia:

Http://symfony.com/doc/current/book/security.html

 44
Author: Cerad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-26 12:25:23

Chociaż jest to bardzo zniechęcające, aby dostać usługi do jednostek, istnieje jest dobry sposób, aby to zrobić, który nie wymaga mieszania się z globalnym jądrem.

Encje doktryny mają zdarzenia cyklu życia, do których można podłączyć detektor zdarzeń, zobacz http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events dla przykładu użyję postLoad, który uruchamia się zaraz po utworzeniu encji.

Lista zdarzeń Może być wykonane jako usługi, do których wstrzykujesz inne usługi.

Dodaj do app / config / config.yml:

services:
     example.listener:
           class: Alef\UserBundle\EventListener\ExampleListener
     arguments:
           - '@alef.role_service'
     tags:
           - { name: doctrine.event_listener, event: postLoad }

Dodaj do swojej jednostki:

 use Alef\UserBundle\Service\RoleService;

 private $roleService;

 public function setRoleService(RoleService $roleService) {
      $this->roleService = $roleService;
 }

I dodaj nowy EventListener:

namespace Alef\UserBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Alef\UserBundle\Service\RoleService;

class ExampleListener
{
     private $roleService;

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

     public function postLoad(LifecycleEventArgs $args)
     {
         $entity = $args->getEntity();
         if(method_exists($entity, 'setRoleService')) {
             $entity->setRoleService($this->roleService);
         }
     }
}
 17
Author: Kai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 18:54:10