开发者

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

开发者 https://www.devze.com 2023-03-13 18:39 出处:网络
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%,

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 开发者_如何学JAVAjust want to do

$user = new User();

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

Thanks for any advice !


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消