How can I create a simple php matching system that works like this?

I am trying to figure out a way to create a hook system very similar to the one used by Drupal. With Drupal, you can simply name the function in a specific way, and it will automatically be called as a hook if the module is enabled.

I examined other answers here in Stackoverflow, but none of them give an answer on how to create this type of function in a PHP application.

+6
source share
4 answers

Here's how drupal does it, and how you can do it. Using string concatenation with naming convention. With the functions function_exists () and call_user_func_array () you must be set.

Here are two internal drupal functions that do the trick (module.inc)

function module_invoke() { $args = func_get_args(); $module = $args[0]; $hook = $args[1]; unset($args[0], $args[1]); $function = $module .'_'. $hook; if (module_hook($module, $hook)) { return call_user_func_array($function, $args); } } function module_hook($module, $hook) { return function_exists($module .'_'. $hook); } 

Therefore you only need to call

 module_invoke('ModuleName','HookName', $arg1, $arg2, $arg3); 

which will finally cause

 ModuleName_HookName($arg1,$arg2,$arg3); 
+8
source

You can use PHP get_defined_functions to get an array of strings of function names and then filter these names in some predefined format.

This example is from PHP docs:

 <?php function myrow($id, $data) { return "<tr><th>$id</th><td>$data</td></tr>\n"; } $arr = get_defined_functions(); print_r($arr); ?> 

Outputs something like this:

 Array ( [internal] => Array ( [0] => zend_version [1] => func_num_args [2] => func_get_arg [3] => func_get_args [4] => strlen [5] => strcmp [6] => strncmp ... [750] => bcscale [751] => bccomp ) [user] => Array ( [0] => myrow ) ) 

This is a kind of sketchy technique compared to a more explicit hook system, but it works.

+3
source

I am not familiar with the internal components of Drupal, but it probably does this with Reflection:

http://php.net/manual/en/book.reflection.php

You would include a PHP page that contains hook functions, then use reflection to find functions or class methods that match a specific naming convention, and then save function pointers to call these functions when necessary (for example, events in the module life cycle) .

+2
source

Why not just use the function? The developer could call the function in a certain way, and the hook codes simply check that they exist and call them

0
source

Source: https://habr.com/ru/post/925734/


All Articles