I know about the dependency injection pattern which seems like the best solution available to handle classes that require instances of other classes to function properly. But when it comes to handling the scenario of a certain class existing, but in a wrong version, DI or any other OOP pattern obviously isn’t going to help at all.
What is a good way to handle version-based dependencies of libraries in PHP?
Here’s an illustrated way to show what I mean (psuedo-code):
class payment_module_base {
var $baseVersion;
function __construct() {
$this->baseversion = 12; //Version 12
}
// Other relevant methods...
}
class card_payments extend payment_module_base {
function construct() {
if ($this->baseversion <= 10)
Throw New Exception("Card payments isnt working with base module V. <10");
}
}
Note: This is for illustrative purposes – I know that this should be lifted out to specific tests to not clutter the production code with conditionals regarding versions unless really neccessary.
A lot of people swear by definitions in the top of library files. It’s simple, and the performance is good … perhaps too simple.
I think it’s a bit unwieldy myself, and prefer factory version management along the lines of …
This model is more extensible. You have to reference the class to get the latest version, but don’t need an instance of it. The reference means that any autoloading code you have will get a chance to pick up the class, and you can run version checks at any point in the pipeline. At the same time, you can optionally support multiple versions of the class, and easily load development versions.
This model also supports building dependency headers …
I would say as a boot note though that PHP doesn’t seem to lend itself well to this kind of arrangement … it’s pretty loose, and requires a fair amount of manual checking to ensure global compatibility. If reasonably possible, I’d avoid versioning in the wonderful world of PHP.
Update: Oh yes, and I almost forgot. You’d very possibly want a class alias along the lines of the following to not require horrible version specific chains.