PHP Abstract Classes
An abstract class is a class that cannot be instantiated. Abstract classes can define abstract methods, which are methods without any body, only a definition:
Abstract classes should be extended by a child class which can then provide the implementation of these abstract methods. The main purpose of a class like this is to provide a kind of template that allows children classes to inherit from, "forcing" a structure to adhere to. Lets elaborate on this with an example:
In this example we will be implementing a Worker interface. First we define the interface:
To ease the development of further Worker implementations, we will create an abstract worker class that already provides the run() method from the interface, but specifies some abstract methods that need to be filled in by any child class:
First of all, we have provided an abstract method getMemoryLimit(). Any class extending from AbstractWorker needs to provide this method and return its memory limit. The AbstractWorker then sets the memory limit and logs it. Secondly the AbstractWorker calls the prepareMain() and main() methods, after logging that they have been called.
Finally, all of these method calls have been grouped in a try-catch block. So if any of the abstract methods defined by the child class throws an exception, we will catch that exception, log it and rethrow it. This prevents all child classes from having to implement this themselves.
Now lets define a child class that extends from the AbstractWorker:
As you can see, the TransactionProcessorWorker was rather easy to implement, as we only had to specify the memory limit and worry about the actual actions that it needed to perform. No error handling is needed in the TransactionProcessorWorker because that is handled in the AbsractWorker.