Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Nikola Poša:
Factory as a Service
Feb 19, 2018 @ 10:53:16

In a post to his site Nikola Poša looks at a method that can be used to provide a slightly different object from a dependency injection container based on other criteria: making use of a factory as a service.

Dependency Injection Containers are a great invention - when used the right way, they allow us to keep our factories and assembly logic of services outside the core business logic of our application.

By default, a service created is shared, meaning that exactly the same instance will be returned whenever service is retrieved from a container. This is a desired behaviour in most of the cases. [...] Yet certain use cases may require services to be created conditionally during runtime, such as for example based on the value of a parameter resolved from the current request.

He first covers some of the anti-patterns that could be used to resolve this issue: a setter method on the returned object, using a service manager or creating a static factory instead. He offers a solution to the problem that makes use of a factory inside of the DI container. This factory then uses configuration values from the container to set up the object and return it.

tagged: factory service dependency injection tutorial database connection

Link: https://blog.nikolaposa.in.rs/2018/02/16/factory-as-a-service/