Implementing a configurable factory
Posted
by Decko
on Stack Overflow
See other posts from Stack Overflow
or by Decko
Published on 2010-04-20T09:14:21Z
Indexed on
2010/04/20
9:23 UTC
Read the original article
Hit count: 339
I'm having difficulties finding out how to implement a 'configurable' behavior in a factory class in PHP.
I've got at class, which takes another class as an argument in its constructor. The argument class could take a number of arguments in its constructor. An instance of my main class could look something like this
$instance = new MyClass(new OtherClass(20, true));
$instance2 = new MyClass(new DifferentClass('test'));
This is rather clumsy and has a number of problems and therefore I would like to move this into a factory class. The problem is that this factory somehow needs to know how to instantiate the argument class, as this class can have any number of arguments in the constructor.
Preferably I would like to be able to do something like this
$instance = Factory::build('OtherClass');
$instance2 = Factory::build('DifferentClass');
And let the factory retrieve the arguments from a configuration array or similar.
Is there a proper solution to this problem?
© Stack Overflow or respective owner