在实体对象中注入或访问服务容器 [英] Injectiong or accessing service container within an entity object

查看:87
本文介绍了在实体对象中注入或访问服务容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用下面的实体访问服务容器,但是如何?



检查了这一点,但是当我正在收听听众时,我迷路了;





控制器

  public function indexAction()
{
$ orders = $ this-> getDoctrine() - > getManager() - > getRepository( 'MyAdminBundle:订单') - >的findAll();
.....
}

实体

 命名空间My\AdminBundle\Entity; 

类订单
{
private $ container;

public function __constructor()
{
$ this-> container =
}

public function getCurrency()
{
return $ this-> container-> getParameter('currency');
}
}


解决方案

Ahmend是正确的,因为你不应该将容器注入实体。在您的情况下,您可能会执行以下操作:

  //控制器
$ order = ... find($ orderId );
$ currency = $ this-> getContainer() - > getParameter('currency');
$ price = $ order-> calculatePrice($ currency);

因此,货币作为方法参数传递。



我完全明白,这是一个困难的概念,特别是如果一个用于活动记录和大量的全局变量。但是最终它会有意义并且产生更好的代码。



但是,只是这样你就不会卡住,我会向你显示访问容器的秘密从任何地方原来,应用程序内核是一个全局变量。所以:

 类订单
{
public function getCurrency()
{
全局$内核;
$ container = $ kernel-> getContainer();
return $ container-> getParameter('currency');
}


I want to access service container withing the entity below but how?

Checked this but I got lost when I was reading listeners;

controller

public function indexAction()
{
   $orders = $this->getDoctrine()->getManager()->getRepository('MyAdminBundle:Orders')->findAll();
   .....
}

entity

namespace My\AdminBundle\Entity;

class Orders
{
   private $container;

   public function __constructor()
   {
      $this->container = ??????
   }

   public function getCurrency()
   {
      return $this->container->getParameter('currency');
   }
}

解决方案

@Ahmend is correct in that you should not inject the container into entities. In your case you might do something like:

// Controller
$order = ...find($orderId);
$currency = $this->getContainer()->getParameter('currency');
$price = $order->calculatePrice($currency);

So currency is passed as a method parameter.

I fully understand that this is a difficult concept especially if one is used to active records and plenty of globals. But in the end it will make sense and produce better code.

However, just so you don't get stuck, I will reveal onto you the secret of accessing the container from anywhere. Turns out that the app kernel is a global variable. So:

class Orders
{
    public function getCurrency()
    {
        global $kernel;
        $container = $kernel->getContainer();
        return $container->getParameter('currency');
    }

这篇关于在实体对象中注入或访问服务容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆