|
| 1 | +# Config Abstract Factory |
| 2 | + |
| 3 | +You can simplify the process of creating factories by adding the |
| 4 | +`ConfigAbstractFactory` to your service manager. This allows you to define |
| 5 | +services using a configuration map, rather than having to create separate |
| 6 | +factories for all your services. |
| 7 | + |
| 8 | +## Enabling |
| 9 | +You can enable the `ConfigAbstractFactory` in the same way that you would enable |
| 10 | +any other abstract factory - in your own code: |
| 11 | + |
| 12 | +```php |
| 13 | +$serviceManager = new ServiceManager(); |
| 14 | +$serviceManager->addAbstractFactory(new ConfigAbstractFactory()); |
| 15 | +``` |
| 16 | + |
| 17 | +Or within any config provider using: |
| 18 | + |
| 19 | +```php |
| 20 | +return [ |
| 21 | + 'service_manager' => [ |
| 22 | + 'abstract_factories' => [ |
| 23 | + ConfigAbstractFactories::class, |
| 24 | + ], |
| 25 | + ], |
| 26 | +]; |
| 27 | +``` |
| 28 | + |
| 29 | +## Configuring |
| 30 | + |
| 31 | +Configuration is done through the `config` service manager key, in an array with |
| 32 | +the key `Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory`. If you are using |
| 33 | +config merging from the MVC/ModuleManager, in this just means that you can |
| 34 | +add a `ConfigAbstractFactory::class` key to your merged config which contains service |
| 35 | +definitions: |
| 36 | + |
| 37 | +```php |
| 38 | +use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; |
| 39 | + |
| 40 | +return [ |
| 41 | + ConfigAbstractFactory::class => [ |
| 42 | + MyInvokableClass::class => [], |
| 43 | + MySimpleClass::class => [ |
| 44 | + Logger::class, |
| 45 | + ], |
| 46 | + Logger::class => [ |
| 47 | + Handler::class, |
| 48 | + ], |
| 49 | + ], |
| 50 | +]; |
| 51 | +``` |
| 52 | + |
| 53 | +The definition tells the service manager how this abstract factory should manage dependencies in |
| 54 | +the classes defined. In the above example, `MySimpleClass` has a single dependency on a `Logger` |
| 55 | +instance. The abstract factory will simply look to fulfil that dependency by calling a `get` |
| 56 | +call with that key on the service manager it is attached to. In this way, you can create the |
| 57 | +correct tree of dependencies to successfully return any given service. Note that `Handler` does not have a |
| 58 | +configuration for the abstract factory, but this would work if `Handler` had a traditional factory and |
| 59 | +can be created by this service manager. |
0 commit comments