2

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');
   }
}
Community
  • 1
  • 1
BentCoder
  • 12,257
  • 22
  • 93
  • 165

2 Answers2

6

@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');
    }
Cerad
  • 48,157
  • 8
  • 90
  • 92
1

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.

Community
  • 1
  • 1
Ahmed Siouani
  • 13,701
  • 12
  • 61
  • 72
  • The question is how am I going to do it? Is there an exampmle you know so that I can go thru? – BentCoder Sep 11 '14 at 09:25
  • Use the currency as a config param, (inject it to services if you need to, ...etc). The question here is why do you think you need to add it to your entity? What's the use case? – Ahmed Siouani Sep 11 '14 at 09:31
  • I have a few data stored in one app/config/site_globals.yml that needs to be read in entity above. That's the whole purpose. – BentCoder Sep 11 '14 at 09:52