Plugin Architecture in PHP
I am planning on doing a research on how to impleme开发者_Go百科nt a plug-in architecture in PHP. I have tried searching the web for possible references, but I thought that maybe my search for a good reference would be faster and more relevant if I asked here.
Has anyone here tried using plug-in architecture for web projects?
Thanks, Erwin
I have written wordpress plugins and the magic that they rely on is "Variable Function Names". For instance this is valid php, in which the function call phpinfo() will be called:
$func_name="phpinfo";
$func_name();
This allows developer to "Hook" function calls, as in override them with their own functions without having change the rest of the application. Linux Kernel modules are all about "hooking", they wouldn't work without this behavior.
Unfortunately for PHP variable function names are a disgusting hack that consumes a lot of resources. All functions in a name space are put in a list and this list has to be searched though before the function is called, this is O(log2(n)). Also keep in mind that Variable Function Names can not be accelerated properly in HipHop although the code will still be transformed into valid C++. A better approach would be to re-declare functions like you can in python which would be O(1) complexity, but the PHP development team HATES this idea (Yes, I've asked for this feature!).
Good luck!
There are a lot of concepts that can be considered a 'plugin'. You can write a plugin system using:
- Event dispatchers (see the Symfony Event Dispatcher)
- Middlewares (see Silex middlewares)
- Observer OO pattern (see Google / Wikipedia)
- And many others
You could take a look at how Zend Framework implemented their Plugin Loader
component.
Basically you set path´s to where plugins are stored and the loader tries to load the first plugin found in a LIFO way.
What about these two classes
- Plugin Handler/Loader
- Plugin
and there are some rules
- Plugin Handler/Loader is a singleton class and manages all child clases of Plugin Class.
- Any plugins should have to be inherited from Plugin Class.
- Plugin Class would have pre-defined properties and methods which can be overwritten by its child classes, so alternate method to hook system (but i am not sure of any major difference in results).
For example say Plugin class has a property of url_routes with default value of an empty array, the child class can then overwrite and add any required urls in this array.
Plugin Handler/Loader will then add these url routes from child class to underlying system.
don't forget about function __autoload. you can dynamically load components. like:
SomeModule::test();
function __autoload($class)
{
$class = preg_replace('/^\W/', '', strtolower($class));
include 'modules/'.$class.'.php';
}
精彩评论