1

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

1
  • My suggestion is to study carefully the section on Services in the reference manual. Services Once you have walked through the process then it becomes trivial to inject the entity manager into MyClass. Commented Feb 8, 2012 at 19:28

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Does this work for the entity? Like to be able to self save the entity? ex: $entity->save()
No. Entities are plain PHP objects. They have no knowledge of the entity manager, nor should they. You're thinking of the Active Record pattern from Doctrine 1. Doctrine 2 uses the Data Mapper pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.