I'm creating a store based on PrestaShop (v 1.6), and I want to register my custom modifier plugin to be accessible from any templates (includinf front and back-officetemplates).
The question is where to place the registration code?
Now I use a Tools class override to add function to handle modifier (that is acceptable practice in case of store-specific functionality, afaik), and smarty.config.inc.php to register plugin (because all PrestaShop plugins are registereg here), but this file contains a warning about "not to modify file directly" and, as far as I understand, will be overwritten when I upgrade PrestaShop.
So, the question is where to register my plugin to be sure that my code will not be overwritten?
Thanks in advance.
You can do this with a module.
1. Create a module
Inside modules folder create a folder testmodule
and inside create a php file testmodule.php
.
We will use a hook actionDispatcher
which executes after every page controller instantiation to register the modifier plugin into smarty.
require_once _PS_MODULE_DIR_ . 'testmodule' . DIRECTORY_SEPARATOR . 'TestClass.php';
class TestModule extends Module {
public function __construct()
{
$this->name = 'testmodule';
$this->tab = 'front_office_features';
$this->version = '1.0';
parent::__construct();
$this->displayName = $this->l('Test Module');
$this->description = $this->l('Testing smarty plugins.');
}
public function install()
{
return parent::install() && $this->registerHook('actionDispatcher');
}
public function hookActionDispatcher()
{
/*
We register the plugin everytime a controller is instantiated
'modifier' - modifier type of plugin
'testToUpper' - plugin tag name to be used in templates,
array('TestClass', 'toUpperMethod') - execute toUpperMethod() from class TestClass when using modifier tag name
*/
$this->context->smarty->registerPlugin('modifier', 'testToUpper', array('TestClass', 'toUpperMethod'));
}
}
2. Create a class which holds the modifier method
In the same module folder create a file TestClass.php
.
In it we will write a static method to execute when smarty plugin is called. For this simple test we will modify any string we want to uppercase.
class TestClass {
public static function toUpperMethod($param)
{
return strtoupper($param);
}
}
Install the module and you can use your plugin in any template for example on front pages
{$page_name|testToUpper}
will echo and transform page name to uppercase.
You could make modifications or safeguards in case you try to use modifier on arrays for example but this is the basics of registering smarty plugins.
No overrides and no core hacking required.