Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Definiton of Symfony Dependency injection container builder from Class factory method?

For example: I have one class which have ClassA::create();

How to register this factory in ContainerBuilder?

$containerBuilder = new ContainerBuilder();

$containerBuilder
    ->register('access_manager', AccessManager::class)
    ->addArgument([new Reference('post_voter')]);
like image 958
Solar Avatar asked Jan 20 '26 22:01

Solar


1 Answers

You call setFactory().

E.g.:

$containerBuilder = new ContainerBuilder();

$containerBuilder
    ->register('access_manager', AccessManager::class)
    ->addArgument([new Reference('post_voter')]);

$containerBuilder->register(ClassA::class)
                  ->setClass(ClassA::class)
                  ->setFactory([ClassA::class, 'create']);

If you want the factory to create new instances of the service each time it's accessed, you'd need to add a call to setShared(false).

Here you can see an example on an online sandbox: https://phpsandbox.io/e/x/qhhxv

(Click on "run" on the bottom right to see it working).

like image 147
yivi Avatar answered Jan 22 '26 13:01

yivi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!