Reputation: 345
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
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:
@service_container
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