I have an application in PHP that is a simplified MVC type structure. This application will be used in over a dozen sites run by my company and others. The structure consists of a controller file, a folder called application which contains the app classes, and a folder called site that contains site specific code such as templates. Periodically, we distribute a patcher that updates the controller and the application folder when we are distributing changes. As a result, clients can’t really alter the core code in the application folder without losing those changes when the code is updated.
I tell you that so I can explain what the clients want – they want the ability to extend existing classes. Is there a design pattern that would allow this? Right now, I have given users the ability to replace entire classes:
spl_autoload_register('loadSiteClass');
spl_autoload_register('loadCoreClass');
This uses an autoloader that checks the site folder for a class before looking in the application folder for the class. I am hoping to find an alternative that would allow me to autodetect, load and use classes that extend existing classes instead of forcing the class to be completely replaced. Any suggestions would be greatly welcomed. Thanks in advance.
If it helps, there is also a site specific config file in the site folder, where the site admin can add config settings telling me that a class is being extended, but I’m still not sure how to use that information if it were provided.
The way codeigniter does it is have a mirror directory structure in the “client” / “application” folder of the system classes. Then you can make a file in the same place as the system class, then simply extend the system class and their loading class will look for the override first and then fallback.
Check here for some code examples: https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Loader.php#L277
Their documentation may be more help to understand their pattern.
I’m sure there are more ways to do this … but generally convention over directory structure and simple PHP “extends” keyword are what makes sense to me.