I need a factory object able to create several objects but in injecting other objects in them. For example:
class MyFactory
{
public function createObjectA() {
return new ObjectA(new ObjectANeededObject1(), new ObjectANeededObject1());
}
public function createObjectB() {
return new ObjectB(new ObjectBNeededObject1(), new ObjectBNeededObject1());
}
}
Should my factory also instantiate the required object (considering my factory is allowed to create any object)? Should I pass them by injection into my factory constructor (but the constructor will contain many many many parameters)? Should I pass them as parameter into my factory method (but the factory client will then know how the object to create should be created and it's not its responsibility to know it)? Should my factory create object builders (able to create my objects and their required objects) instead of my object directly?
What do you recommand?
Thank you,
Ben
Your class Factory
should not know how to instanciate an object from class ObjectBNeededObject1
, because if the constructor changes, you will have to go back also to the class Factory
and do the necessary job to avoid a regression
UPDATED
class MyFactory
{
public static function createObjectA($object1, $object2) {
return new ObjectA($object1, $object2);
}
public static function createObjectB($object1, $object2) {
return new ObjectB($object1, $object2);
}
}
$objectA = MyFactory->createObjectA(new ObjectANeededObject1(), new ObjectANeededObject1());
$objectB = MyFactory->createObjectB(new ObjectANeededObject1(), new ObjectANeededObject1());