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);
}
Related
In a joomla menu item page i placed same module instances multiple times(i duplicated in module manager).Now it's a severe requirement that some codes of my module have to be only one time in page.Because my module's each instance injects same code again and again.
how to avoid it so that only some codes will appear in page only once when i have multiple module instances of my module in that same page?
searching through web i found some unreliable ways -
1.Using session in module i track whether same module loading two or more times and restrict code injecting one time only
2.using a constant like this way -
if(!defined('MODULE_ALREADY_LOADED')){
//echo codes that you only want done once
//this will set the constant and now the other modules won't load/echo the code
define('MODULE_ALREADY_LOADED', true);
}
But not sure how much compatible the 2nd way is with joomla 2.5 as well as joomla 3 versions !.If there is a better error free way to do this then provide to me asap.
in your module code, you can use addscript method (it checks the duplicate scripts) instead of writing js directly. So, externalize your scripts, then in your code :
$document = JFactory::getDocument();
$document->addScript('your_script.js');
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 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.
In a Drupal 7 (and Drupal 6?) system, what "kicks off" the hook calling process, or where are "top level" hook calls located?
As I currently understand the Drupal module system, any module is capable of creating a hook for another module to implement. That means much of Drupal's execution is modules implementing hooks for other modules, which in turn provide hooks for other modules to implement.
What I'm not clear on is if there's a initial, top level hook that gets called in the bootstrap to kick this process off, or if there's several non-module calls that kick-off the hook invoking process, or something else (apologies is this is vague and newbish, but like I said I don't understand)
I looked in the _drupal_bootstrap_full function, and at the end there was a promising
module_invoke_all('init');
However, my search of the modules/ folder only turned up one "init" hook function, which didn't appear to be a kick off point
system/system.api.php
1737:function hook_init() {
function hook_init() {
drupal_add_css(drupal_get_path('module', 'book') . '/book.css');
}
So, that says to me something outside the module systems kicks this whole things off. Does this happen in a single place, or multiple places. And where are these places?
I'm not currently a heavy Drupal user. My end goal of all this is understanding Drupal's module system in isolation, so that I can then investigate and understand how Drupal uses it's modules the build the application most people think of as Drupal. Any/all explanations are welcome, but I'm trying to understand things from an architectural point of view. I understand you don't need this knowledge to use Drupal, but my brain is broken and won't let me move forward until I know what the base PHP code is doing.
The hook system is one separated system inside of Drupal. It is not responsible for the bootstrapping. hook_init() is just the hook that is called at the end of the bootstrap process. As the other answer said, module_invoke_all() can be called anytime, anywhere in the process.
Put simply, in Drupal 7, the following two lines in index.php are responsible for the very basic flow of a request:
<?php
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();
?>
Which can be translated into two steps:
Bootstrap the system. This includes loading all modules and necessary include files, database connection and so on.
Look for the menu router item responsible for this request and execute it.
Someone started a series of blog post to describe it in more details, see http://becircle.com/blog_topics/line_line.
module_invoke_all is where it all happens.
From the doc: Invoke a hook in all enabled modules that implement it.
Init probably isn't a good one as very few define it. Also, remember that hooks are called and not hook.
Edit:
/**
* Deletes a node type from the database.
*
* #param $type
* The machine-readable name of the node type to be deleted.
*/
function node_type_delete($type) {
$info = node_get_types('type', $type);
db_query("DELETE FROM {node_type} WHERE type = '%s'", $type);
module_invoke_all('node_type', 'delete', $info);
}
This is in D6 node.module. This is an example of invoking a hook from module code, in this case hook_node_type, with two arguments.
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.)