Injectiong or accessing service container within an entity object

蓝咒 提交于 2020-01-04 09:17:11

问题


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

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

  • Get service container from entity in symfony

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

回答1:


@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');
    }



回答2:


As explained in the link you shared: An entity is a data model and should only hold data (and not have any dependencies on services). You should then find another clean way to do what you want to do.

Based on your code, one may suppose that the value of currency is defined in your configuration (unless you inject it in your container some other way). It's definitely not relevant to tight it to one of your entities.



来源:https://stackoverflow.com/questions/25783094/injectiong-or-accessing-service-container-within-an-entity-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!