How can I access a container in a class that is not a service in Symfony 2

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 access the container without inserting it.

Basically i just wanna do

 $user = new User(); 

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

Thanks for any advice!

+1
source share
1 answer

Well, you don’t have direct access to the controller from inside the object if you don’t enter it (this is most likely a bad idea, by the way) ... but if you want your kinorm_pdo service kinorm_pdo be accessible from your User class just paste this ( provided that you instantiate the class from the context supporting the container):

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

or even

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

Note that it looks like you are trying to provide access to the database from within the object ... sharing problems says this is probably not the cleanest way to accomplish everything you are trying to do ... if you provide a little more information about what you are trying to accomplish, we may also help you with this.

+4
source

Source: https://habr.com/ru/post/1487866/


All Articles