1

I have a service defined in my config.yml

services:
  kinorm_pdo:
    class: Pate\KinormBundle\Dbal\Db
    arguments: [%kinorm.db_driver%,%kinorm.db_user%,%kinorm.db_pass%,%kinorm.db_name%,%kinorm.db_host%,%kinorm.db_charset%]

But I want to have access to this service in a class that is not a controller and I do not understand how to gain access to the container without injecting it.

Basicly I just want to do

$user = new User();

and have inside $user access to the container...

Thanks for any advice !

Paté
  • 1,914
  • 2
  • 22
  • 33

1 Answers1

4

Well, you don't have direct access to the controller from inside an object unless you do inject it (which is most likely a bad idea, by the way)... but if you want your kinorm_pdo service available from your User class, just inject that (assuming that you're instantiating the class from a container-aware context):

$user = new User($this->container->get('kinorm_pdo'));

or even

$user = new User();
$user->setPdo($this->container->get('kinorm_pdo'));

Note that it sounds like you're trying to provide access to the database from inside an entity... separation of concerns says this is probably not the cleanest way to accomplish whatever you're trying to do... if you provide a little more information on what you're trying to accomplish, we can probably help you with that, as well.

Problematic
  • 17,567
  • 10
  • 73
  • 85
  • Well you understood completly, I'm trying to have access to my db from my models, I just don't get why I can't do queries in my object. I found so many case where creating a repository just seems weird... – Paté Jun 17 '11 at 10:12
  • I agree with Problematic. It is much better to put your methods into a repository and then pass in a User to the repository method. The Doctrine repositories are already aware of which EntityManager to use and then your problem disappears. – markymark Jun 20 '11 at 08:41
  • Yes, this is a difference form how things have been done in the past, for better or worse. @markymark is totally correct that you should get into the habit of putting your methods into your repository and passing the user object to that method (e.g. `getSomeComplicatedInformationForUser($user)`). This is a bit more work and you may have to prepare more for your template in the controller, but it is a slightly cleaner pattern overall. – weaverryan Dec 24 '11 at 20:04