简体   繁体   中英

Register functions or strings into Symfony dependency injection container

I would like to use Symfony di container to register anonymous functions or strings. Ideally using PSR11 API, something like this:

$containerBuilder = new ContainerBuilder();
$containerBuilder->register('databasehost', '127.0.0.1');
$containerBuilder->register('Database', function($c) {
   return new Database($c->get('databasehost'));
};
$containerBuilder->get('Database')->insertInto(...);

Is it possible? How?

databasehost is a parameter, while you're trying to register it as a service. Instead, you should set it via setParameter method to make it indeed a parameter.

Then you can use it to inject into service with addArgument method.

There's a very similar example in DIC Component docs :

$containerBuilder = new ContainerBuilder();
$containerBuilder->setParameter('mailer.transport', 'sendmail');
$containerBuilder
    ->register('mailer', 'Mailer')
    ->addArgument('%mailer.transport%');

So your code should be something like:

$containerBuilder = new ContainerBuilder();
$containerBuilder->setParameter('databasehost', '127.0.0.1');
$containerBuilder
    ->register('Database', 'Database')
    ->addArgument('%databasehost%');

And by the way, PSR-11 does not say anything about building the cointainer, but only about retrieving services from it. It defines only get and has methods.

PS I assumed that Datatabase what just a typo and you meant Database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM