phpdependency-injectionsubclasspimple

PHP Dependency Injection Container With Factory


I'm working with silexphp/Pimple Dependency Injection Containers (DIC) and am unsure how to handle what would be a classic Factory pattern.

Example:

A parent class Animal.php has two child classes called DogAnimal.php and CatAnimal.php. The number of child classes can grow.

In this case I'd want to create a Factory for creating new Animal Objects or children of the Animal class. Pimple does allow one to create Factory methods per service.

While using Pimple DIC I don't think I'd want to add each subclass (Dog, Cat, etc) as a service. Especially as the list grows. To me that seems like a misuse of the DIC but perhaps I'm wrong.

Am I correct in assuming that I should be creating an Animal Factory service and using Pimple to inject dependencies to the factory which in turn gets used to create a new Dog or Cat?


Solution

  • Yes, you're right. You can create a service (AnimalFactory) that creates the object you want to use (DogAnimal, CatAnimal, ...).

    A simple example can be:

    class AnimalFactory
    {
        public function createAnimal($name)
        {
            // some logic here with $name
    
            $animal = new ...();
            return $animal;
        }
    }
    
    $pimple['animal_factory'] = function ($c) {
        return new AnimalFactory();
    };
    
    $dog = $pimple['animal_factory']->createAnimal('Dog');