views:

25

answers:

1

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?

+1  A: 

If you store the list of classes and their constructor arguments as an array. Something like:

array(
    'OtherClass' => array(20, true),
)

You can then construct the class using the reflection api and the newInstanceArgs function.

Yacoby
That was just what I was looking for. I'm actually already using the reflection api in other parts of the code, so this works out great. Thanks!
Decko