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')]);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With