I have been asked to do a project where the client can create PHP plugins and add them to the website… same concept as WordPress plugins.
What is the best way to make a software that supports that? I'm not asking for the solution, I'm asking for the concept or structure.
First of all, you have to determine how do you want your plugins integrated. If you want something like Wordpress plugins, which are just plain functions most of the times, then it's extremely easy. It's like adding new code to your application.
Well, basically, your application should be able to build a list of plugins available, and to determine which ones are enabled. The list can be built by browsing the files, a config file, or whatever. Enabled plugins can be stored in the database for example.
Then, you just do an interface where the user can enable each available plugin. When enabling it, the web application would write information about it in the plugins database, specifying that it's enabled. Then, the application calls a specific method of the plugin class (really, OOP is mandatory in correct plugin development), like Install(). To avoid exceptions when plugins have no such method, all plugin classes should inherit a base class written in the main web application, which does contain a definition for that method. That method has the sole purpose to perform the initialization of the plugin (create tables to the database, populate statistics, etc).
Also, at each request, your web application should include all the files of the plugins that are specified as enabled. Then use them however you want. Call their methods from templates for example. If you want to write plugins that are transparent to the template developer, then you could do just like in wordpress. There, the plugin at initialization (for example when it's file is included) writes specific data into arrays of actions. It can write what function should be called, with what parameters, and when to be called.
You can even make something like event triggers in your main web application, to enable customization. Before drawing something, call a function called something like do_action("before_output_of_something"), and after output is ended, call the function do_action("after_output_of_something"). The string parameter would be a key in an array of triggers, that points to an array of actions (event handlers). To add event handlers call a function like this add_action("before_output_of_something", $object, "method_name", array("parameters")). do_action method passes the array of actions, and uses call_user_func() PHP function to call event handlers.
There is much more to this topic. All depends on what exactly you want to make.
What I wrote here is just a lousy attempt to express some of the possibilities. What you should do is find a good book, maybe about just this topic.
I would solve this by using the event-dispatcher pattern. You define certain points (events) in your main application. Plugins can register for this events and will be executed, when the related event is triggered.
There are multiple options. Most common is the hooks concept with simple plugin functions, where you just have to include() a plugin from a central configuration script. Each plugin has to register itself, so usually there is a plugin registration method. But it can also just look like this:
$app_plugin["add_title"][] = "do_whatever";
function do_whatever($request, &$page) {...}
And in your main application you just define a couple of plugin calls, wherever you see the need for it. You would use a wrapper function to invoke all plugins, but basically you look for the hook name and invoke all registered plugins:
foreach ($app_plugin["add_title"] as $func) {
$output .= $func($_REQUEST, $page);
Each named hook can have a different set of parameters. Typically you would want to get additional content, but sometimes plugins just modify existing variables, or influence the application flow.
The more hooks you have, the more diverse extensions are possible. And it's not necessary to use functions only. Of course this scheme also works with objects (they just need to be instantiated first.)
Related
I've built my own CMS for learning purposes (and also just for fun), but now I would like to expand it, so that it supports some basic form of extensions (plugins). I would like to work with some kind of observer-pattern where extensions register themselves by the ExtensionManager for certain updates (for example onRenderTitle()). Every extension would consist of one mandatory class ExtensionData that would be executed for every extension in the system. The extensions could register themselves in this class by using a callback (the ExtensionManager would be passed on to every ExtensionData class).
But now every extension has to register itself with every page load (because PHP loses state between every page load), causing potential performance problems.
Am I doing this completely wrong? Or is this the way to go? I have no experience in writing a CMS that supports extensions (that's what I'm trying to learn). I looked at how Wordpress works with extensions, but I haven't found how it loads them up.
Plugins in Wordpress are registered just by being placed in the wp-content/plugins folder, and they have to have the necessary docblocks in its main file. It is also a convention in WP that your plugin's main file has the same name as your plugin plus the .php extension, e.g. plugins/myplugin/myplugin.php.
As far as interaction with the core of your CMS goes, you can have your system to fire events and the plugins would then listen for them. WP uses actions and filters for it. Your code for a simple event listener could look following then:
action('action_name', function() {
// some code to be executed after event is fired
});
Your action() function could just update a global array of actions. When you want to fire the event, you just filter through the array of assigned actions.
foreach ($actions['action_name'] as $func) {
call_user_func($func);
}
Summary:
Do pre-controller hooks execute during caching? Is there any hook-point which will execute? (pre-system?)
I should probably highlight the fact that the hook doesn't affect the content that is sent to the browser. That isn't an issue.
Detailed version:
I plan on implementing some statistics-type functionality in a project I've built using PHP and CodeIgniter.
The project in question is a custom built CMS - due to the extended intervals between updates I've used caching to help speed up load times; this isn't essential but it's preferential. It seems to be a good solution to a largely static site; especially where dynamic content is primarily served client-side - i.e AJAX requests.
The proposed functionality primarily involves a pre-controller hook which accesses methods through libraries such as the User Agent library, before dumping them to a database. From here it can be polled, outputted via JSON and manipulated before being displayed by something like the jQuery flot plugin.
I've read through the documentation on the Web Page Caching as well as the documentation regarding hooks. Unfortunately, it's still not clear whether using caching will completely bypass the hooks.
I'm aware of the cache_override however this means implementing your own caching mechanism; not what I want to do!
The alternative would be gathering statistics client side and submitting it to the server via AJAX; but this isn't ideal either as I'm trying to have a clear separation of logic - for maintenance and testing reasons.
In short:
Do pre-controller hooks execute during caching? No.
Is there any hook-point which will execute? Yes pre_system does execute.
If caching kicks at system/core/CodeIgniter.php:189, the only hook that gets a chance to run is pre_system (system/core/CodeIgniter:124).
Unfortunately you don't get much functionality of codeigniter at that point, no get_instance() and without that most core libraries are not loaded as well. If you are inclined you can look into what functions are defined inside system/core/Common.php thats pretty much all you got.
If you are really want to make this work with the built in classes you can sort of fight your way to a database object and other core stuff like this:
You will have to manually get the BASEPATH.'database/DB.php' file included in. Fortunately in the loader class, it loaded with require_once so it won't break the page on cache miss.
Once you got the Database library loaded instantiate the usual $this->db object with calling DB(). Without parameters it will load the default database from the config files as usual.
At this point you can write your queries from your pre_system hook, and since hooks can be objects, you can move every logging code inside the hook's object. If you need other libraries you can get an instance of them with the load_class() function (don't forget to set the third prefix parameter to empty string if you are not loading a built in class).
At the end you should end up like this (imaginary code):
class MyLoggingHook {
// called from the hook config
public function run($params = array()) {
require_once(BASEPATH.'database/DB.php');
$db = DB(); // getting hold of a DAO instance
// routing information is always useful to have for pageview logs
$RTR = load_class('Router', 'core');
$RTR->_set_routing();
// Router also load Uri and Config classes inside so the following two instances could be interesting too:
// $RTR->uri
// $RTR->config
// load some useful library not related to CodeIgniter
$user_agent_detector = load_class('UserAgentDetector', 'libraries', '');
// do some logging
$db->insert('page_view_log', array('class' => $RTR->fetch_class(), 'method' => $RTR->fetch_method(), /*...*/);
}
}
I should probably mention that i've never used something like this in production and there's the risk of relaying on funcionality that could change from version to version. If you can do without touching the Codeigniter classes inside your hook go with that.
Using PDO for database access, loading the database config with get_config(), you can get by without touching any codeigniter related classes.
I'm trying to think of a way to create a plugin architecture for my own framework. I've read numerous topics and post here and on other sites. And basically i've came to the following solution which seems to be the only good option in PHP (currently).
The idea is that every class extends a sort of observer like class. So a Template class, BaseController etc. always extend a Plugin class.
class BaseController extends Plugin
{
public function __construct()
{
// Plugin check, notify all loaded plugins
$this->checkForEarlyHooks();
// Init some standard stuff
$this->view = new Template();
$this->baseLayout = 'layout.html';
$this->something = new Something();
// Plugin check, notify all loaded plugins
$this->checkForLateHooks();
}
}
So what basically happends here is that when an indexController extends a baseController a plugin check is done. In this case for the constructor. This can be convenient when you want to do a some sort of login check with a plugin, before an Action method is actually invoked.
The Plugin class can resolve from what class is got called from and knows for what functions to look for in the loaded plugins.
Also note that it checks the loaded plugin list 2 times. One before anything is loaded (early) in the constructor, and one when all vars are loaded (late).
I can also add variables to the "checkForLateHooks()" function. So the hook functions can manipulate those too, like the 'baseLayout' variable.
A hook function would look like this:
public function hookConstruct ( &$baseLayout )
{
$baseLayout = 'login.html';
}
Now basically my question is, is this approach any good? I know there are probably alot of other ways to do it too. But i mainly don't want to run into design problems later on. It seems like a good idea now, but you never know how things work out later on...
If i remember it right (from all the posts the i've read), this is kinda like WordPress does it (and some other frameworks).
UPDATE: answer now reflects the up-to-date links and better description.
There are certainly many different ways to design a plugin system and perhaps asking on https://softwareengineering.stackexchange.com/ would give you more ideas, but I'll try to help by sharing my ideas and experience.
I'll share some of my own experiences which I've learned through a series of my own frameworks. Currently Agile UI and Agile Data both support many wasy to be extended, but I'll focus on the "Components"
HOOKS
When you look to inject code into the existing object, a hook is a standard way to go. It's the best option for extending the application or flow with an established structure.
While refactoring my frameworks, I've separated hook implementation into a separate trait and documented it here: http://agile-core.readthedocs.io/en/develop/hook.html
Host application:
... some code here ..
$this->hook('beforeInit');
$this->init();
$this->hook('afterInit');
... code goes on ..
Plugin:
$host_app->addHook('beforeInit', function($object) {
echo "About to execute init of $object";
});
UI COMPONENTS
Components present a different design pattern, which is suitable for the User Interfaces. You start with the page/app layout which is then broken down into Menu, Header, Footer, Content.
A component is an object which can be associated with Layout or the other component. Each component is capable of rendering and passing extra HTML/JS to its parent. Most of components would also be an interractive objects.
This approach is called "Render Tree" and application execution goes through 2 stages - "initialization of a render tree" and then "rendering".
Host Application:
$layout->menu = new \atk4\ui\Menu();
$layout->add($layout->menu, 'TopMenu');
The above code show how a new Component (Menu) can be initialized and inserted into the $layou. Furthermore the HTML output of $menu is directed into {$TopMenu} tag, which is defined in the HTML template of Layout.
Plug-in can interact with the render tree by:
adding more components anywhere in the tree
affecting existing components (e.g. add new menu item)
destroying any of the existing components
When those approaches are combined, you can use something like this:
$app->addHook('afterInitLayout', function($app) {
$app->layout->menu->destroy(); // remove default menu
$app->layout->menu = new \plugin\SuperMenu();
$app->layout->add($app->layout->menu);
});
This can be used to replace standard menu with a more powerful implementation from your add-on.
My implementation of components is documented here:
http://agile-ui.readthedocs.io/en/latest/view.html#initializing-render-tree
UI / DATA SEPARATION
Although perhaps not so much answer for a question, but another powerful way to extending is a separation of concerns. All of the UI components in Agile UI do not know how to do anything with data.
While many UI generators require developer to manually build them up and link up with data, I am injecting "Model" object like this:
$form->setModel(new User($db)); // populates name, surname and gender fields
Demo: http://ui.agiletoolkit.org/demos/form2.php (2nd form)
In this approach object User contains enough meta-data for the Form to populate it's fields, captions perform validation and also save/load data.
Since "User" class can also be declared in an add-on it makes a pretty powerful way to extend existing functionality by adding support for new data entities.
OTHER APPROACHES
Some other approaches to extend with add-ons include:
Factory:
The ability to resolve class specified as a string into namespace / file:
$api->add('MyClass');
Gives ability for add-on to re-route standard classes but is not very friendly with type-hinting in IDEs.
New types / Traits:
Add-on can provide new classes adding Persistences, Table Columns, Form Fields, Actions etc.
CONCLUSION
I think add-on deign boils down to:
simplicity of installation and use
does add-on need to operate out-of-the-box?
avoiding conflicts between add-ons
defining different add-on types - authentication, UI, behaviour
can add-on extend another add-on
will add-on fit application design, data and architecture?
give a lot of power to add-ons without sacrificing performance
Have a look at PHPPlugin on https://github.com/gheevel/PHPPlugin. A simple PHP plugin framework inspired by eclipse and jira plugin architectures. Basically, your application can define extension points and plugin instances can register on those extension points for providing extra functionality. Works well in combination with composer and/or symfony.
I am trying to build a basic plugin system like the kind you often find in a CMS like WordPress. You have a folder of plugins which tie into the main system's operation through event notifications using an Observer or Event design pattern.
The problem is it's impossible for the system to know which events the plugin wants to act upon - so the system has to load each plugin for every page request just to find out if that plugin is actually needed at some point. Needless to say, that's a lot of wasted resources right there--in the case of WordPress, that adds up to several extra MB of memory for each request!
Are there alternative ways to do this?
For example, is there a way to load all this once and then cache the results so that your system knows how to lazy-load plugins? In other words, the system loads a configuration file that specifies all the events that plugin wishes to tie into and then saves it in APC or something for future requests?
If that also performs poorly, then perhaps there is a special file-structure that could be used to make educated guesses about when certain plugins are unneeded to fulfill the request.
I do have a plugin management tool, but I only every used it with predominantly procedural plugins, and with all includes usually loaded at once. But for an event-based and lazy-loading API I could imagine using shallow wrappers for the plugin management, and resorting to autoloading for the actual extensions.
<?php
/**
* api: whatever
* version: 0.1
* title: plugin example
* description: ...
* config: <var name="cfg[pretty]" type="boolean" ...>
* depends: otherplugin
*/
$plugins["title_event"] = "TitleEventClass";
$plugins["secondary"] = array("Class2", "callback");
?>
In this example I'd assume the plugin API is a plain list. This example feature-plugin-123.php script would do nothing but add to an array when loaded. So even if you have a dozen feature plugins, it would only incur an extra include_once each.
But the main application / or plugin API could instead just instantiate the mentioned classes (either new $eventcb; for the raw classnames or call_user_func_array for the callbacks). Where in turn it would offload the actual task to an autoloader. Thus you have a dual system, where one part manages the list, the other locates the real code.
I'm thereby still imaganing a simple config.php which just lists plugins and settings like this:
<?php
include_once("user/feature-plugin-123.php");
include_once("user/otherplugin2.php");
include_once("user/wrapper-for-htmlpurifier.php");
$cfg["pretty"] = 1;
Again taking in mind that these are just wrappers / data scripts, with the plugin description for managability. One could as well use an actual register_even() API and define an additional wrapper function in each. But listing classnames seems the simplest option.
The aforementioned management tool is kind of rusty and ugly: http://milki.include-once.org/genericplugins/
But it's uneeded if you just need a list (sql table) and no settings management. That overhead is only for prettyprinting the plugin meta data and keeping a human-readable config.php.
In conclusion:
spl_autoload() on the include_path, and a simple event->classname registry, one wrapper script each, simply included all at once.
Wordpress and other CMS systems are very bad examples.
What we have to understand is that modular, almost always means heavier.
The best scheme that I ever worked with to solve this situation is a class based plugin, with a strict naming convention using an auto loader.
So, before using the plugin, you´ll need to create an instance, or use static functions.
You can even call the plugin like:
<?php $thePlugin::method(); ?>
eg:
<?php
spl_autoload_register('systemAutoload');
function systemAutoload($class)
{
$parts = explode('_',$class);
switch($parts[1])
{
case "Plugin":
include("/plugins/{$parts[2]}/{$parts[2]}.php");
break;
}
// ...
}
?>
Regarding Events:
You have to register this events statically to avoid bringing it in a dynamic manner.
The database would be the right place to do it. You can have an events table, and install() and uninstall() methods on the plugin class to add specific events or bind methods to other events. It´s one database query, and if you want more from it, add it to memcached, or to a flat ini file.
Works well for me. This way I was able to get a heavy system that was consuming 8mb per request to drop to 1mb, with the exactly same list of features, without advanced caching. Now we can add more features and mantain the system "clean"
Hope that helps
I would save the plugin class name along with it's subscribed events in a configuration file and then save the parsed config file in APC, for example. Then when an event is triggered the system can lazy load the appropriate plugin classes as needed.
I am planning on doing a research on how to implement 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';
}