user1014102
user1014102

Reputation: 345

Symfony2 dependencies in class

I try to create a class to manage some part of my app but I need to access the configuration in resources/config.yml

I tryed to extends my class with containerAware as a controler But he container is not set...

I would like to be able to do something like that:

class MyClass extends ContainerAware
{
   public function myFunciton()
   {
      $em = $this->get('Doctrine')->getEntityManager();
   }
}

any suggestion is welcome

Upvotes: 1

Views: 1512

Answers (1)

Steven Mercatante
Steven Mercatante

Reputation: 25315

Extending ContainerAware does not automatically grant access to the service container - you would need to inject the container into your class. There are two ways to do that:

  • If your class is registered as a service, you can inject @service_container
  • If your class is not a service, but is being accessed from a class that does have access to the container (like a controller), you can explicitly call setContainer()

That being said, you should not inject the container into your classes. This makes it harder to test your classes. There are a few exceptions to this, but they don't come up often.

Instead, you should only inject services you need. In the case of the entity manager, you would inject @doctrine.orm.default_entity_manager.

In regards to accessing data from a config.yml, I would suggest including the file (which can be done when defining a service) and parsing the yml using either Symfony\Component\Yaml\Parser or Symfony\Component\Yaml\Yaml. The parsers converts a yml string to a PHP variable that you can then easily work with.

Upvotes: 4

Related Questions