I have a system that uses an auto loader to load a class. I am able to edit the auto loader, but I want people to be able to extend one of my classes and have my system still run.
Lets say class A is the original and class B is the new one that extends class A.
I have:
A.php
namespace Core;
class A{}
B.php
namespace Core;
class B extends OverriddenA{} ( Explained below )
When the autoloader loads A - instead of actually loading A, I want it to load B, which requires the real A to be loaded. So it should look like this:
include 'A.php';
class_alias('A', 'OverriddenA');
include 'B.php';
class_alias('B', 'A');
The problem is that the second class_alias()
errors because A is already loaded as A.
Presently the only solution I can think of is to do a file_read_contents(), replace the class name and run an eval() - but I would really hate to do that.
Ok I found a great way to do this.
The class that the system will look for is Core\A
So that file is actually created as Overridable\A
When it's loaded, the class loader sees that it's overridable so it looks if it's overridden. If it is, it loads the override which already declares itself as Core\A extends Overridable\A
If there is no override, but it's in the Overridable namespace, it creates an alias: class_alias(Overridable\A, Core\A);
And just so my IDE can still be able to reference everything, I create a file called Overrides.php which is never actually included that just says:
namespace: Core;
class A overrides \Overridable\A {}