【问题标题】:Injectiong or accessing service container within an entity object在实体对象中注入或访问服务容器
【发布时间】:2014-09-11 08:52:20
【问题描述】:

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

检查了这个,但我在阅读听众时迷路了;

控制器

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

实体

namespace My\AdminBundle\Entity;

class Orders
{
   private $container;

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

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

【问题讨论】:

    标签: symfony doctrine-orm


    【解决方案1】:

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

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

    所以货币作为方法参数传递。

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

    但是,为了不让您卡住,我将向您揭示从任何地方访问容器的秘密。原来,应用程序内核是一个全局变量。所以:

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

    【讨论】:

    • global $kernel; 正是我想要的 :) 谢谢
    【解决方案2】:

    the link you shared: An entity is a data model and should only hold data (and not have any dependencies on services) 中所述。然后,您应该找到另一种干净的方式来做您想做的事情。

    根据您的代码,您可能会认为currency 的值是在您的配置中定义的(除非您以其他方式将其注入您的container)。绝对不相关将其与您的实体之一紧密联系。

    【讨论】:

    • 问题是我要怎么做?有没有你知道的例子让我可以通过?
    • 使用货币作为配置参数,(如果需要,将其注入服务,...等)。这里的问题是为什么你认为你需要将它添加到你的实体中?用例是什么?
    • 我有一些数据存储在一个 app/config/site_globals.yml 中,需要在上面的实体中读取。这就是全部目的。
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多