See the 6 Comments
Dynamic Hooks with the __call() Method
Original article written by Vincent Augagneur-Core Developer
Translated to English by Benjamin Utterack-Community Manager
When developing a module for PrestaShop that appears in different locations, or hooks, in the back or front office, we use the integrated hook system in PrestaShop to “graft: the module anywhere you want.
The system works great. However, as with any system, there are some limitations. We will provide you a trick that will help to lessen the effect of these limitations and make the entire system much more fluid.
A Hook needs several things to work:
- a method in the module class of the public function hookTest()
- a call to the method $this-> registerHook (‘hook_name’); during the installation of the module.
Once the module is installed, it is not possible for a merchant or visitor to add or remove a hook dynamically.
Here is one trick you can use:
Imagine that the module receives information via a WebService or a call to a remote API. This Web Service would send the list of banners to display on the site corresponding to its respected PrestaShop hook.
During the call to the web Service, the module will automatically be “hooked” so that it can display the banner in the right place:
$banners = array(
array(‘img’ => ‘url_de l’image1’, ‘hook’ => ‘displayHome’),
array(‘img’ => ‘url_de l’image2’, ‘hook’ => displayFooterProduct),
foreach ($banners as $banner)
if (Validate::isHookName($banner[‘hook’]) && !$this->isRegisteredInHook($banner[‘hook’]))
//here you can save in database images and hook name related
The module can now be added to any hook you wish. Now what is left is to make the hook dynamic. In order to do this, we will use the magic method __call() in the following way:
public function __call($name, $arguments)
$hook_name = str_replace('hook', '', $name);
//here you can get all images to display in the database, by using hook name for exemple.
$banners = Banner::getByHookName($hook_name);
The applications of this method are multiple and limitless. Feel free to respond to propose improvements or simply ask questions.
Receive articles like this in your inbox!
Subscribe to get the latest ecommerce news and tips sent directly to your email. Subscribe