I want to write a simple class (PHP5) that can ‘run’ an unknown amount of subclasses. These subclasses are best translated as ‘checks’; they all will more or less do the same thing and give an answer (true / false). Think of it as system startup checks.
Over time new checks (subclasses) will be added to a directory and they should automatically be run when the main class is invoked. Others may write checks but they will have to follow the functions dictated by the main class.
What would be a clean yet simple way to build this?
I found the Factory pattern and combined with interface it seems a good starting point. However I am not sure, and I would appreciate advice on this.
EDIT: the provided answers here all work, however the answer by Gordon gives additional possibilities of batches and stacking, something I did not think of at the time of asking, but am now rather happy about.
If you want to create a Batch-like functionality, use the Command Pattern.
Below is a very simple implementation of the pattern. The idea is to have a unified interface for all classes you want to invoke. Each class encapsulates one operation in the batch:
One class implementing the interface will be the commander of all subclasses:
A simple Command could look like this:
You could then use it like this:
Because BatchCommander is a BatchCommand itself, you can easily stack batches belonging together into other Batches, thus creating a very flexible tree structure, e.g.
In your Check/Test context, this means you could group conceptually belonging single tests into a test suite. And you can create test suites of test suites, by stacking one suite into another.
Of course, you could also give the BatchCommander a file path to check on instantiation and have it init all BatchCommands by running through the files in the file path. Or pass it a Factory instance to use for creating the Check commands.
You don’t have to have
executeandundofor method names. Name itcheckif you want. Leave outundoif you don’t need it. The basic idea still stays the same though: one interface for all classes to be commanded, whatever that may look like. Feel free to adapt.An alternative with a somewhat different UseCase is the Chain of Reponsibility pattern. Check it out to see if this would be of utility too.