In my project I’m processing data and working with the results. There is an abstract class which looks like the following:
class AbstractInterpreter
{
public function interprete( $data )
{
throw new Exception('Abstract Parent, nothing implemented here');
}
}
And then there are various different implementations of the AbstractInterpreter:
class FooInterpreter extends AbstractInterpreter
{
public function interprete( $data )
{
return "resultFoo";
}
}
class BarInterpreter extends AbstractInterpreter
{
public function interprete( $data )
{
return "resultBar";
}
}
My calling code creates the interpreters and collects the results:
//this is the data we're working with
$data = "AnyData";
//create the interpreters
$interpreters = array();
$foo = new FooInterpreter();
$bar = new BarInterpreter();
$interpreters[] = $foo;
$interpreters[] = $bar;
//collect the results
$results = array();
foreach ($interpreters as $currentInterpreter)
{
$results[] = $currentInterpreter->interprete($data);
}
I’m currently creating more and more interpreters and the code gets messy… For each interpreter I need to add a certain include_once(..) and I have to instantiate it and put it into the $interpreters.
Now, to finally ask my question:
Is it possible to automatically include and instantiate all interpreters that are in a specific directory and put them into the $interpreters?
In other languages this would be some kind of a plugin-concept:
I create different implementations of AbstractInterpreter, put them in a specific subdirectory and the software uses them automatically. I would not have to modify the code which loads the interpreters as soon as it is finished.
I don’t know if it’s possible automatically, but you can write a few lines code to get the same result.
Name your class files as InterpreterName.php and put into the same directory, for example plugings
And yes, this looks messy.