How to create custom PrestaShop hook

Автор: Richard Smaizys
Опубликованно: 5 октября 2010
Источник: How to create custom PrestaShop hook

PrestaShop hooks are great way to insert or add data at the most important places or actions of this great e-commerce platform. However, I am not satisfied with the quantity of default hooks and I sometimes use custom hooks with my custom modules. So how to implement custom hook and why not hard code all code without it?

Why hook is the right choice?

There is one big problem in my opinion with custom hooks because you need to hard code their position into the files that might be affected by CMS updates or etc. So it is just more easier to add one line of code than to copy and paste a bunch of code or even all page of it.

Secondly, hooks are easy used in modules which lets you save time and avoid headaches. You do not need to think about default page code as you just add addition to it, for example, you will not delete necessary code by accident.

Thirdly, it is just a good practice and manner of good and professional programmer.

How to create custom hook?

All active hooks are hold in Prestashop database table called ps_hook (ps_ is default database prefix and it will be on this article too), so you have to add it on module installation.

1DB::getInstance()->execute("INSERT INTO `"._DB_PREFIX_."hook`
2                            SET `name`= 'nameYourHook',
3                                `title`= 'Hook Title',
4                                `description`= 'Hook description'
5                           ");

After you added hook information to the database, you must register it for later you which you do by calling this method:

1$this->registerHook('nameYourHook');

Now you can easily insert your hook anywhere in the code.

However, it depends if you want it to execute raw PHP code or it will return a template file. There are two options and both are shown below.

1Module::hookExec('nameYourHook');

With Smarty:

1$smarty->assign(array(
2        'MY_HOOK' => Module::hookExec('cat')));
3$smarty->display(_PS_THEME_DIR_.'template_file.tpl');

If you use the example with smarty, you must add {$MY_HOOK} variable where you want into your .tpl file that gets this assign. That’s about it.

Now you can add whatever you want to hooks function which you write like this:

1function hookNameYourHook($params) {
2         // Your hook actions comes here
3}

Try it yourself.