i'm working silexphp/pimple
dependency injection containers (dic) , unsure how handle classic factory pattern.
example:
a parent class animal.php
has 2 child classes called doganimal.php
, catanimal.php
. number of child classes can grow.
in case i'd want create factory creating new animal objects or children of animal class. pimple allow 1 create factory methods per service.
while using pimple dic don't think i'd want add each subclass (dog, cat, etc) service. list grows. me seems misuse of dic perhaps i'm wrong.
am correct in assuming should creating animal factory service , using pimple inject dependencies factory in turn gets used create new dog or cat?
yes, you're right. can create service (animalfactory
) creates object want use (doganimal
, catanimal
, ...).
a simple example can be:
class animalfactory { public function createanimal($name) { // logic here $name $animal = new ...(); return $animal; } } $pimple['animal_factory'] = function ($c) { return new animalfactory(); }; $dog = $pimple['animal_factory']->createanimal('dog');
Comments
Post a Comment