4

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?

1 Answer 1

3

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks for the sanity check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.