php Symfony 2.0 在实体内部获取服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10330704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:55:47  来源:igfitidea点击:

Symfony 2.0 getting service inside entity

phpservicesymfonydoctrine-ormentity

提问by Kaminari

Im seraching over and cannot find answer. I have database role model in my application. User can have a role but this role must be stored into database.

我搜索并找不到答案。我的应用程序中有数据库角色模型。用户可以有一个角色,但这个角色必须存储到数据库中。

But then user needs to have default role added from database. So i created a service:

但是用户需要从数据库中添加默认角色。所以我创建了一个服务:

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

}

my services.ymlis:

我的services.yml是:

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

And now I want to use it in two places: UserControllerand Userentity. How can i get them inside entity? As for controller i think i just need to:

现在我想在两个地方使用它: UserControllerUser实体。我怎样才能让它们进入实体?至于控制器,我想我只需要:

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

But how to get service inside entity?

但是如何在实体内部获得服务?

回答by Cerad

You don't. This is a very common question. Entities should only know about other entities and not about the entity manager or other high level services. It can be a bit of a challenge to make the transition to this way of developing but it's usually worth it.

你没有。这是一个很常见的问题。实体应该只知道其他实体,而不是实体管理器或其他高级服务。过渡到这种开发方式可能有点挑战,但通常是值得的。

What you want to do is to load the role when you load the user. Typically you will end up with a UserProvider which does this sort of thing. Have you read through the sections on security? That should be your starting point:

你要做的是在加载用户的时候加载角色。通常,您最终会得到一个执行此类操作的 UserProvider。您是否通读了有关安全性的部分?这应该是你的起点:

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

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

回答by Kai

While it's very discouraged to get services into entities, there isa nice way to do it that does not involve messing with the global kernel.

虽然非常不鼓励将服务放入实体中,但一种很好的方法可以做到这一点,而不会涉及与全局内核的混乱。

Doctrine entities have lifeCycle events which you can hook an event listener to, see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-eventsFor the sake of the example, I'll use postLoad, which triggers soon after the Entity is created.

主义实体拥有,你可以挂钩一个事件侦听器生命周期事件,看到http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events为求在示例中,我将使用 postLoad,它会在实体创建后不久触发。

EventListeners canbe made as services which you inject other services into.

EventListeners可以作为您注入其他服务的服务。

Add to app/config/config.yml:

添加到 app/config/config.yml:

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

Add to your Entity:

添加到您的实体:

 use Alef\UserBundle\Service\RoleService;

 private $roleService;

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

And add the new EventListener:

并添加新的 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);
         }
     }
}