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.
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);
}
Ok this is just something I feel I should ask as I could not find any reference to this in any kind of documentation, and reading through the actual code to figure out the best way to accomplish this would take far longer then hope to spend.
When you enter the Article manager you have a navigation link to the Category manager and vice versa. I would like to do something similar with my component and the default User manager.
I already have a profile plugin to extend the users to suit my needs, but I would like the configuration of it seamless so adjusting the com_user component to integrate better with my component is what I am looking for.
So my question is with the com_content and com_categories they use the "extension" parameter. Is it possible to add similar functionality without a full core override of the com_users? If I do a full override there is a chance of some extensions not working due to reliance on the users.
I am willing to clarify if anything does not make sense, this question is more to see the extent you can "extend" Joomla without overrides.
UPDATE:
I have found a cool technique, not quite an answer though.
You can override just the list controller/model/view in your component, and if you based it off of the current com_users component you can make it look like a direct integration.
The only edits you need to do is making sure any routes to the users view instead pass to your component.
There is one issue with this however, when you add a new user or edit one, once you finish it will direct you to the main user manager. A system plugin may help with this but only if there is a reliable way to detect when the user was edited through your component, rather then the users manager.
Note: The problem with adding an override to the user view is that it has 5-6 other MVC components it relies on, so in the interest of making it easy to update with core com_users updates it is best to avoid that if at all possible.
Another thing needed is to make sure to find the language file for com_users and add all entries to your component.
I feel there may still be a better answer out there, but doing it this way does not impact the core much, and would be easy to update with updates to com_users.
I am opening a bounty on this, I feel of every question I ever asked this is one that will have the most benefit to the community. So here is a condensed version of the question.
What would be an easy way to integrate a core component into a custom component and have it route through that component seamlessly with the least edits to the core component.
I'm not exactly clear on what you want but if you're talking about the toolbar submenu's like this in com_content:
The example you give of Categories (i.e. com_categories) is specific support added where you can pass in a link to com_catgories with your extension identifier (the extension=com_mycomponent) and it will load the sidebar menu for your extension. This is so core categories can be shared amongst various components [see Add Categories].
You may already be aware of the following, but, if you want to know how to add a sidebar menu to your components manager view you can call JHtmlSidebar::addEntry($title, $link, $active);
Typically this is put in your extensions primary helper file in a function called addSubmenu($vName) (which is what & where com_categories will look for to display your toolbar sub-menu). Its called addSubmenu() because the sidebar morphed from being the toolbar submenu in previous versions of Joomla.
e.g. this is the addSubmenu() method in the ContentHelper class defined in administrator/com_content/helpers/content.php
/**
* Configure the Linkbar.
*
* #param string $vName The name of the active view.
*
* #return void
* #since 1.6
*/
public static function addSubmenu($vName)
{
JHtmlSidebar::addEntry(
JText::_('JGLOBAL_ARTICLES'),
'index.php?option=com_content&view=articles',
$vName == 'articles'
);
JHtmlSidebar::addEntry(
JText::_('COM_CONTENT_SUBMENU_CATEGORIES'),
'index.php?option=com_categories&extension=com_content',
$vName == 'categories');
JHtmlSidebar::addEntry(
JText::_('COM_CONTENT_SUBMENU_FEATURED'),
'index.php?option=com_content&view=featured',
$vName == 'featured'
);
}
By comparison the com_categories helper class CategoriesHelper has a very different addSubmenu() method which looks for the calling extensions core helper class (if one isn't found it defaults to com_content).
There isn't any support like that in com_users so you will probably have to create a system plugin that fires onAfterRoute and adds your submenu item based whether or not your component has provided a suitable parameter, like the extension=com_myextension. It would be a bit of a swizzle but it should work — the only thing is as you would be adding a submenu item before the component is dispatched your new submenu item would like always be the first item in the com_users submenu. It wouldn't be a complete replacement like com_categories supports.
Unfortunately there aren't any triggers in com_users that I can find that would be of any help in swizzling the entire sidebar menu.
The next option is to use something like Donald Gilbert's gist to create a system plugin that allows you to override any core class by creating a substitute version of your own — obviously this will have issues with any significant updates but if you're careful you could limit the override to your specific situation.
If thats not enough/overkill you may want to try a system plugin that responds to onAfterDispatch at which point you would have the page before its returned to browser and you could hack the HTML, but thats very ugly and be prone to breaking if users change their admin template.
Of course, I could be completely wrong and theres a better way to do it in 3.x. Maybe someone else will chime in.
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 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.)