Php function call hook

PHP How to create simple hook?

Add an event Then call it like this Or remove all callbacks for that event like this Solution 2: Here’s another solution: Creating a hook Run this wherever you want to create a hook : Attach a function to the hook Then attach a function to the above by doing: Global variable to store all hooks/events Add this to the top of your main PHP functions file, or equivalent Base functions Solution 3: this solutions has some problems that you can’t set several function for one callable hook. The developer could name the function in a certain way, and the hook codes just check that it exist then call them Question: How can I make hooks in php.

PHP How to create simple hook?

I already tried to Google how to do this, but I still can’t figure it out. How do I create a simple hook in side PHP? Here is what I’ve tried so far:

wrapper.php (application starts here)

 //supposed to execute specific hook function executeHook($hookname) < global $hooks; foreach($hooks[$hookname] as $funct)< call_user_func( $funct ); >> //supposed to execute action in $hooks when array key = hook_head function hook_head() < global $hooks; if (array_key_exists('hook_head', $hooks)) < executeHook( 'hook_head' ); >> //supposed to execute action in $hooks when array key == hook_footer function hook_footer() < global $hooks; if (array_key_exists('hook_footer', $hooks)) < executeHook( 'hook_footer' ); >> ?> 

The code works fine if I insert an action inside $hooks[‘hook_head’] , before I call hook_head() . What I actually am trying to do though, is insert the action after I called hook_head() . How do I do this?

Читайте также:  text-align

Move the addHook call to before the hook_head call (preferably to the beginning of the file).

I did notice that you «want to start coding (insert action in hook head) after it call hook_head()», but that’s very cumbersome. It would look something like that:

  • Change hook_head() to insert some kind of token into the output.
  • At the end of the script,
    1. call ob_get_clean() to get the output buffer of the page.
    2. For each hook:
      1. Execute the hook.
      2. Call ob_get_clean() again to get the output buffer of the hook.
      3. Replace the appropriate token in the oputput buffer of the page with the output buffer of the hook.
    3. Print the output buffer of the page.

As I said: cumbersome. I strongly advice against it. I only mentioned it because you asked specifically. It contradicts the intuitive control flow of

Run php script with webhook, I have php script on my server and app sending webhooks. I need the scenario: When webhook sent — run php script on my vps. Webhook is successfully sent (checked with webhook test) but if i put an address of php as a link for webhook it still doesn’t run. Php script is okay. Its just simple fwrite:

How to do a PHP hook system?

How do you impliment a hook system in a PHP application to change the code before or after it executes. How would the basic architecture of a hookloader class be for a PHP CMS (or even a simple application). How then could this be extended into a full plugins/modules loader?

(Also, are there any books or tutorials on a CMS hook system?)

You can build an events system as simple or complex as you want it.

/** * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called. * * @param string $event name * @param mixed $value the optional value to pass to each callback * @param mixed $callback the method or function to call - FALSE to remove all callbacks for event */ function event($event, $value = NULL, $callback = NULL) < static $events; // Adding or removing a callback? if($callback !== NULL) < if($callback) < $events[$event][] = $callback; >else < unset($events[$event]); >> elseif(isset($events[$event])) // Fire a callback < foreach($events[$event] as $function) < $value = call_user_func($function, $value); >return $value; > > 
event('filter_text', NULL, function($text) < return htmlspecialchars($text); >); // add more as needed event('filter_text', NULL, function($text) < return nl2br($text); >); // OR like this //event('filter_text', NULL, 'nl2br'); 
$text = event('filter_text', $_POST['text']); 

Or remove all callbacks for that event like this

event('filter_text', null, false); 

Creating a hook

Run this wherever you want to create a hook :

Attach a function to the hook

Then attach a function to the above by doing:

x_add_action('header_scripts','my_function_attach_header_scripts'); function my_function_attach_header_scripts($values) < /* add my scripts here */ >

Global variable to store all hooks/events

Add this to the top of your main PHP functions file, or equivalent

$x_events = array(); global $x_events; 

Base functions

function x_do_action($hook, $value = NULL) < global $x_events; if (isset($x_events[$hook])) < foreach($x_events[$hook] as $function) < if (function_exists($function)) < call_user_func($function, $value); >> > > function x_add_action($hook, $func, $val = NULL)

this solutions has some problems that you can’t set several function for one callable hook. you can fallow this code.

 $action = []; function apply($hook, $args) < global $action; $action[$hook]['args'] = $args; return doa($hook, $args); >function add($hook, $func) < global $action; $action[$hook]['funcs'][] = $func; >function doa($hook,$args) < global $action; if(isset($action[$hook]['funcs']))< foreach($action[$hook]['funcs'] as $k =>$func) < call_user_func_array($func, $args); >> > add('this_is', 'addOne'); function addOne($user)< echo "this is test add one $user 
"; > add('this_is', function()< echo 'this is test add two
'; >); add('this_is_2', 'addTwo'); function addTwo($user, $name)< echo $user . ' ' . $name . '
'; > function test()< echo 'hello one
'; apply('this_is', ['user'=> 123]); > function test2()< echo 'hello two
'; apply('this_is_2', ['user'=> 123, 'name' => 'mohammad']); > test(); test2();

Php — How do I create a webhook?, A webhook url is a place on your server where the above providers will send data from time to time when something happens and you need to know about, for example you might get a request each time a sms is sent, or each time a sms fails sending and based on that info you can take further actions, like …

How would I build a simple php hook system that works like this?

I am trying to figure out a way to build a hook system very similar to the one that Drupal uses. With Drupal you can simply name a function a certain way and it will automatically be invoked as a hook if the module is enabled.

I have looked at the other answers here on Stackoverflow, but none of them really give an answer of how to build this type of feature into a PHP application.

This is how drupal does it, and how you can do it. Using string concatenation with name convention. With function_exists() and call_user_func_array() you should be all set.

Here are the two internal drupal functions that make 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)

Therefore, you only need to invoke

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

You could use PHP’s get_defined_functions to get an array of strings of function names, then filter those names by some predefined format.

This sample from the PHP docs:

$id$data\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 ) ) 

It’s kinda a sketchy technique when compared to a more explicit hook system, but it works.

I’m not familiar with Drupal internals, but it probably does it using Reflection:

You would include the PHP page that contains the hook functions , then use reflection to find functions or class methods that match a certain naming convention, then save function-pointers to call those functions when appropriate (such as events in a module’s lifecycle).

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

Event-driven architecture and hooks in PHP, Code snippet(s) showing how to put a «hook» in a function in PHP. The manual link above (callbacks can be stored into a variable) and some PHP code examples for the Observer Pattern. Share. Follow edited Jul 27, 2011 at 15:04. answered Jul 27, 2011 at 14:39. hakre hakre.

How to make hooks in php

How can I make hooks in php . I am not sure on how wordpress process their Hooks . This is a short example that I wanted to do.

I have a script tag on my register.php file and I wanted it to move on the ****

I need an example on how to do this. Thanks in advance.

Look here: http://components.symfony-project.org/event-dispatcher/

It’s a small and powerful hook library with full documentation

I think you should take a look at one design pattern called observer pattern .

Oop — Hooking method execution in PHP, php oop hook. Share. Follow asked Jun 22, 2011 at 15:38. Wagemage Wagemage. 280 1 1 gold badge 4 4 silver badges 10 10 bronze badges. 1. Make your methods private and execute them using the magic method __call – datasage. Jun 22, 2011 at 15:43. Add a comment |

Источник

Хуки в PHP — расширение функций и контроллеров ядра

Многие функции и методы CS-Cart (Multi-Vendor) имеют специальные хуки.

Хуки позволяют модифицировать и расширять возможности платформы с помощью модуля.

  • Изменять входящие параметры функции
  • Дополнять логику работы функции
  • Влиять на результат работы функции
  • Выполнять собственную функцию при выполнении стандартной функции

Хуки расположены в функциях и методах ядра CS-Cart.

Общий принцип использования и работы с хуками:

  1. Определились с необходимыми изменениями стандартной функциональности
  2. Нашли подходящий хук, рядом с местом необходимых изменений, вам обязательно встретятся хуки в процессе п. 1
  3. Подключились к хуку своим модулем и внесли нужные изменения.

Доступно очень много хуков:

Как выглядт и как использовать хук?

fn_set_hook('hook_name', $param1, $param2, $param3, $param4); 

Чтобы подключиться к хуку, вам необходимо:

    Инициализировать подключение к хуку. В своём модуле откройте или создайте файл app/addons/[id_модуля]/init.php . В данный файл добавьте функцию:

php if (!defined('BOOTSTRAP'))  die('Access denied'); > fn_register_hooks( 'hook_name' ); 
fn_register_hooks( 'hook_name', 'hook_name_2', 'hook_name_3', ); 
// Создаём функцию, которая подключится к хуку. function fn_[id_модуля]_hook_name(&$param1, &$param2, &$param3, &$param4)  // Изменяем нужны параметр $param1 = 'новое значение'; > 

Живой пример

Предположим, что нам нужно добавить какую то новую информацию о товаре, если товара нет на складе.

Функция fn_get_product_data() получает информацию о товаре для карточки товара (и много ещё где используется). Данная функция находится в файле app/fucntions/fn.catalog.php .

// В начале функции, все входящие параметры доступны. fn_set_hook('get_product_data_pre', $product_id, $auth, $lang_code, $field_list, $get_add_pairs, $get_main_pair, $get_taxes, $get_qty_discounts, $preview, $features, $skip_company_condition); // В середине функции, перед SQL запросом, чтобы можно было расширить SQL запрос. fn_set_hook('get_product_data', $product_id, $field_list, $join, $auth, $lang_code, $condition); // В конце, доступен результат работы функции — массив с данными о товара $product_data fn_set_hook('get_product_data_post', $product_data, $auth, $preview, $lang_code); 

Подключимся к последнему хуку и добавим нужную нам информацию с помощью модуля “Мои изменения”:

    Создадим файл app/addons/my_changes/init.php , чтобы инициализировать подключение к хуку. Добавим в него код:

php if (!defined('BOOTSTRAP'))  die('Access denied'); > fn_register_hooks( 'get_product_data_post' ); 
php if (!defined('BOOTSTRAP'))  die('Access denied'); > // Создаём функцию, которая подключится к хуку. function fn_my_changes_get_product_data_post(&$product_data, $auth, $preview, $lang_code)  if ($product_data  0)  $product_data['new_info'] = 'Bam Bam Bigelow'; > > 

Как проверить что оно работает?

Используйте функцию fn_print_r($product_data); до хука, после хука или внутри хука. Она распечатает на экран содержимое массива.

Как я могу использовать именно этот пример?

Создайте новую вкладку с SMARTY блоком для карточки товара. В данном SMARTY блоке вы можете использовать информацию из массива , в том числе вашу новую информацию, например, для каких либо условий.

Содержание

Сейчас

Источник

Оцените статью