<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NemoPS &#187; hook</title>
	<atom:link href="http://nemops.com/tag/hook/feed/" rel="self" type="application/rss+xml" />
	<link>http://nemops.com</link>
	<description>Prestashop Tutorials, Modules and More!</description>
	<lastBuildDate>Wed, 05 Dec 2018 13:25:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.35</generator>
	<item>
		<title>Target specific pages from a Prestashop Module&#8217;s Hook</title>
		<link>http://nemops.com/page-specific-prestashop-module/</link>
		<comments>http://nemops.com/page-specific-prestashop-module/#comments</comments>
		<pubDate>Mon, 17 Jun 2013 09:49:30 +0000</pubDate>
		<dc:creator><![CDATA[Nemo]]></dc:creator>
				<category><![CDATA[Tips n Tricks]]></category>
		<category><![CDATA[hook]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[page]]></category>

		<guid isPermaLink="false">http://nemops.com/?p=1361</guid>
		<description><![CDATA[<p>You can easily restrict a Prestashop module&#8217;s display by adding exceptions in the back office positions. However, if you automate the process, there is a small trick that can be used when creating a module&#8217;s hook, which will also open a whole set of new possibilities to display page-specific content. The php_self context variable Each [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://nemops.com/page-specific-prestashop-module/">Target specific pages from a Prestashop Module&#8217;s Hook</a> appeared first on <a rel="nofollow" href="http://nemops.com">NemoPS</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>You can easily restrict a Prestashop module&#8217;s display by adding exceptions in the back office positions. However, if you automate the process, there is a small trick that can be used when creating a module&#8217;s hook, which will also open a whole set of new possibilities to display page-specific content.</p>
<p><span id="more-1361"></span></p>
<h2>The php_self context variable</h2>
<p>Each Prestashop page has its own name, setup in the appropriate controller. It&#8217;s the body id assigned to a page as the $page_name variable in smarty. However, if you tried to get the page name from within a module, you might have noticed it&#8217;s only assigned to smarty. So is there a way to target each specific page from within a module? Yes, indeed. Here is the code:</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;context-&gt;controller-&gt;php_self
</pre>
<p>It can be really useful if you only want to <strong>target specific pages within a module</strong>. Let&#8217;s see a practical example.</p>
<h2>Target specific pages from a module&#8217;s hook</h2>
<p>Say, for the only sake of this example, that we only want to display a top of pages module if the current page is the homepage. Let&#8217;s use blocksearch.</p>
<p>In this case, We would only need to edit blocksearch.php, locate the <strong>hookTop</strong> method:</p>
<pre class="brush: php; title: ; notranslate">

	public function hookTop($params)
	{
		if (!$this-&gt;isCached('blocksearch-top.tpl', $this-&gt;getCacheId('blocksearch-top')))
		{
			$this-&gt;calculHookCommon($params);
			$this-&gt;smarty-&gt;assign('blocksearch_type', 'top');
		}

		return $this-&gt;display(__FILE__, 'blocksearch-top.tpl', $this-&gt;getCacheId('blocksearch-top'));
	}
</pre>
<p>And add this at the beginning of the function:</p>
<pre class="brush: php; title: ; notranslate">
if('index' != $this-&gt;context-&gt;controller-&gt;php_self)
	return false;
</pre>
<p>We a re simply telling it: if the current page is not the homepage, kill the module so it doesn&#8217;t display anything.</p>
<p>Just think at the possibilities at this point: <strong>you can display different content, and do diffrent things from the same hook, depending on the current page.</strong></p>
<p>How to? First, decide the pages that need specific behaviors. Use <strong>var_dump($this->context->controller->php_self)</strong> to check each page&#8217;s exact name. Then simply add a switch or if operator, that checks the current page name and acts properly each time, like:</p>
<pre class="brush: php; title: ; notranslate">
if('index' == $this-&gt;context-&gt;controller-&gt;php_self)
	// Do something and display a template for the homepage
else if('category' == $this-&gt;context-&gt;controller-&gt;php_self)
	// Do something and display a template if we are in the category page
else // not in any of the 2 pages above
	return false: // don't display anything
</pre>
<p>The post <a rel="nofollow" href="http://nemops.com/page-specific-prestashop-module/">Target specific pages from a Prestashop Module&#8217;s Hook</a> appeared first on <a rel="nofollow" href="http://nemops.com">NemoPS</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nemops.com/page-specific-prestashop-module/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>A deeper look at Prestashop Hooks</title>
		<link>http://nemops.com/a-deeper-look-at-prestashop-hooks/</link>
		<comments>http://nemops.com/a-deeper-look-at-prestashop-hooks/#comments</comments>
		<pubDate>Thu, 23 Aug 2012 08:09:49 +0000</pubDate>
		<dc:creator><![CDATA[Nemo]]></dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[hook]]></category>
		<category><![CDATA[module]]></category>

		<guid isPermaLink="false">http://nemops.com/?p=173</guid>
		<description><![CDATA[<p>Today, we are going to cover one of the most overlooked feature of Prestashop: Hooks. I&#8217;ll be teaching you what these mysterious entities really are, and how to bend them to your will, and bring your site to the next level of customization. What are hooks? If you have been using Prestashop for quite some [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://nemops.com/a-deeper-look-at-prestashop-hooks/">A deeper look at Prestashop Hooks</a> appeared first on <a rel="nofollow" href="http://nemops.com">NemoPS</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>Today, we are going to cover one of the most overlooked feature of Prestashop: Hooks. I&#8217;ll be teaching you what these mysterious entities really are, and how to bend them to your will, and bring your site to the next level of customization.<br />
<span id="more-173"></span><br />
<a class="download-files button style1" href="http://nemops.com/wp-content/uploads/2012/08/testing.rar" title="Download Project Files">Download Project Files</a></p>
<h2><strong>What are hooks?</strong></h2>
<p>If you have been using Prestashop for quite some time, I bet you found yourself saying “Why in the world can’t I place something there? I really want to do it!” in more than one occasion. Yes, it can be frustrating, because Prestashop only allows you to execute your modules in specific spots, defined by the software itself. These places are commonly known as <strong>hooks</strong>. And this is actually all what hooks are, as the name suggests: they represent definite points of the code which you can use to run your own module’s functions.</p>
<p>If this may be considered as a limitation, since it forces the developer to only use those specific points to run a module’s code without touching the core files, it’s also a powerful and easy solution to greatly improve Prestashop’s basics functionalities. Actually, hooks make your life A LOT easier when extending the package. At least, you don’t have to mess for ages with XML and Zend Framework ugly PHP (have I heard someone screaming Magento?).</p>
<p>Anyway, if you are a developer, and know how to code a prestashop module, you’ll be quite used to the following structure:</p>
<pre class="brush:php">public function hookLeftColumn($params)
{
    /* Code to be executed */
}</pre>
<p>This function allows the module to be hooked to the left column, and running proper code from there, be it something to display to the user, or stas gathering stuff. In any case, you will <strong>always</strong> need to run a <em>hookSomewhere</em> function to run the module’s code in a specific place.</p>
<div class="separator"></div>
<p>&nbsp;</p>
<h2><strong>Visual Hooks VS Action Hooks</strong></h2>
<p>Hooks can be basically grouped into 2 main groups: <strong>Visual Hooks</strong>, and <strong>Action Hooks</strong>.</p>
<p>The first ones are generally used to display content to your website, and provide a visual feedback to the customer. While there are in fact back Office visual hooks, like the one used to display new tabs on the Stats page, most of them are defined by controllers in front office, and assigned to variables to be executed within the template. An example of this is the “Left Column” hook we saw previously, used to show modules on the left column of the base template</p>
<p>&nbsp;</p>
<p>Action hooks are, on the other side, deputed to only run code, without actually display content. They are placed both in class and controller files, and may come in handy when we need to gather data thrown by a class, manipulate it, or use it for  purposes other than Prestashop’s default one. As the name suggests, they occur when a spacific action takes place. An example of action hook is the “cart” hook, executed in the Cart.php Class when a cart is created or updated.</p>
<p>To exemplify, let’s say we have a “best sales” module, and it uses database caching to optimize performance. It retrieves best sellers from a cached version of the product list created once in a while. Well, this once in a while can be set in two ways: the traditional way is to set up a cron job, and refresh the list once every hour, or day, or so; the other way would be using hooks. We could hook the module to “<strong>newOrder</strong>”, which is a hook that executes when a new order is placed, and code a function that refreshes data in that particular moment. This way, there would be now need to fetch all product data every time the page reloads, thus increasing our site’s speed. Of course, this is just an example (taken from one of my modules, Best sales of the day/week/month/period, which you can find <a title="here" href="http://store.nemops.com/modules/14-best-sales-of-the-day-week-month-period.html" target="_blank"><strong><span style="text-decoration: underline;">here</span></strong></a>), and there are other many things you can do with action hooks.</p>
<p>Whichever purpose hooks have, they all share the same basic structure:</p>
<ul>
<li><strong>A database entry in the ps_hook table </strong></li>
</ul>
<p><img class="aligncenter size-large wp-image-184" style="color: #333333; font-style: normal; margin-top: 0.4em;" title="Prestashop Hooks table" src="http://nemops.com/wp-content/uploads/2012/08/php_my_admin-680x144.png" alt="Prestashop Hooks table" width="680" height="144" /></p>
<p>This is the core part of the hooks, since it’s what makes Prestashop know whether the specific hook we are currently calling exists or not.</p>
<p>&nbsp;</p>
<ul>
<li><strong> The <em>hookExec()</em> function which executes it</strong></li>
</ul>
<p>It’s the function that runs the hooks execution, and therefore all hook<em>NameOfTheHook</em>() function associated to it(see next). The function is defined in the Module Class, and can be passed a number of parameters to be stored in the <strong>$params</strong> variable of the executing function.</p>
<pre class="brush:php">Module::hookExec('nameofthehook')</pre>
<pre class="brush:php">Module::hookExec('nameofthehook', $params_array)</pre>
<p>When creating a front office visual hook, instead of directly executing the hooks attached modules, the action is assigned to a variable to be called by smarty within the template.</p>
<pre class="brush:php">self::$smarty-&gt;assign('HOOK_NAMEOFTHEHOOK', Module::hookExec('nameofthehook'));</pre>
<p>In this case, you would also need to add the following code to the template file where you wanted to display the hook’s content</p>
<pre class="brush:php">{$HOOK_NAMEOFTHEHOOK}</pre>
<p><strong><br />
</strong></p>
<ul>
<li><strong>A <em>hookNameOfTheHook()</em> function to be placed in modules in order to hook them</strong></li>
</ul>
<p>Without this, a module would not be hooked to anything and would never execute. This last function is the most important one, since it allows you to perform any action for the desired hook. We already saw the code for the <em>HookLeftColumn()</em> function.</p>
<pre class="brush:php">public function hookLeftColumn($params)
{
    /* Code to be executed */
}</pre>
<p>This function usually returns a template file in front office hooks</p>
<pre class="brush:php">return $this-&gt;display(__FILE__, 'filename.tpl')</pre>
<p>&nbsp;</p>
<div class="separator"></div>
<p>&nbsp;</p>
<h2>Let’s go into action: creating a new Hook in Prestashop</h2>
<p>Now that we know enough about hooks, let’s create a new hook that will allow us to display modules content at the beginning of  each category page.</p>
<p>The first step will be to let Prestashop know the hook exists, so let’s add it to the database. We can go 2 ways: log in to phpmyadmin (or any sql manager) and add the column manually; or create a module which, when installed, will add the hook.</p>
<p><strong>The database way:</strong></p>
<p>Log in to your sql manager. In your prestashop database, look for the table ps_hook (remember, ps_ is just the default prefix, you can have anything instead of that! Take note of your prefix). If you’re using phpMyAdmin, click on the <em>yourprefix</em><strong>Hook</strong> table, then Insert, and add values for the name (which should be all underscore and without spaces), title and description then click add. Alternatively, you can use run this SQL query:</p>
<pre class="brush:php">INSERT INTO `ps_hook` (`name`, `title`, `description`) 
VALUES ('category', 'Category', 'Hooks before the product list in a category');</pre>
<p>&nbsp;</p>
<p><strong>The module way:</strong></p>
<p>If the hook is only used by a module, we can also bind it to the module itself, and add it in the installation process. Let&#8217;s create a function that looks like this:</p>
<pre class="brush:php">protected function addHook() {
    $check = Db::getInstance()-&gt;getRow('
			SELECT name
			FROM '._DB_PREFIX_.'hook
			WHERE name = "category"
			');

    if (!$check) {
	$query = "INSERT INTO "._DB_PREFIX_."hook (`name`, `title`, `description`) VALUES ('category', 'Category', 'Hooks before the product list in a category');";
	if(Db::getInstance()-&gt;Execute($query))
	    return true;
	else
	    return false;
    }
    else return true;
}</pre>
<p>The $check part is useful to know if another hook with the same name exists, since creating douplicates will definitely cause problems!</p>
<p>&nbsp;</p>
<p><strong>Executing the hook</strong></p>
<p>Now that prestashop has the hook data stored, it’s time to run it’s execution</p>
<pre class="brush:php">self::$smarty-&gt;assign('HOOK_CATEGORY', Module::hookExec('category'));</pre>
<p>We can place this code in the FrontController.php file, or any other controller, since we are going to use the hook for display purposes. Using the FrontController saves us the time of thinking where exactly it should run, because assigning the variable in the DisplayHeader function will set it for every front page, before even one of the other hooks is assigned. So, to add the assignment to the Front Controller, let’s create a new FrontController.php file, place it into override/classes, and fill it with the following code.</p>
<pre class="brush:php"></pre>
<pre class="brush:php">&lt;?php 

Class FrontController extends FrontControllerCore
{

	public function displayHeader()
	{
		if (!self::$initialized)
			 $this-&gt;init();

			self::$smarty-&gt;assign('HOOK_CATEGORY', Module::hookExec('category'));

		parent::displayHeader();		
	}

}</pre>
<p>&nbsp;</p>
<p>Note the if (!self::$initialized)  $this-&gt;init(); snippet at the beginning of the function. This ensures the controller is properly initialized, and fixes problems in pages such as payment or order confirmation..</p>
<p>Even though using the front controller saves us the time of having to scrub through all other controllers to find the right position to execute it, be aware that it will be assigning the execution for every front page of the shop. So, for our purposes, it would have been better to add the assignment in the <em>process()</em> function of the <strong>CategoryController</strong>. In the end, of course, the choice is all up to you. For the sake of it, here is what adding the code to a categoryController override would have looked like</p>
<pre class="brush:php">class CategoryController extends CategoryControllerCore
{

    public function process()
    {
        parent::process();
        if (!($id_category = (int)Tools::getValue('id_category')) OR !Validate::isUnsignedId($id_category))
            $this-&gt;errors[] = Tools::displayError('Missing category ID');
	else
		{
                     self::$smarty-&gt;assign('HOOK_CATEGORY', Module::hookExec('category'));
          }
    }
}</pre>
<p>&nbsp;</p>
<p><strong>Now, let’s add the hook to the template</strong></p>
<p>Let’s open up the category.tpl file of our template.Just before this code</p>
<pre class="brush:php">{if $products}</pre>
<p>Which is line 90 of the prestashop_new template, add the following</p>
<pre class="brush:php">{$HOOK_CATEGORY}</pre>
<p>Most of the work it’s done, and we have just successfully added a new hook in Prestashop!</p>
<div class="separator"></div>
<h2>Creating a module to be hooked</h2>
<p>…Yay, okay, but we need to test this new hook, or else we don’t know if it really works or not. I’ve prepared a testing module, which can be found as an attachment at the beginning of the post. Grab it, copy the “testing” folder inside the <em>modules</em> folder and open the testing.php file.</p>
<p>If you know something about modules, you’ll definitely know they have to be <strong>registered</strong> to a hook before they can be executed. If you don’t want to do it manually from the positions tab in back office, add the following code in the <em>install()</em> function:</p>
<pre class="brush:php">public function install()
{
    if (!parent::install() OR
	!$this-&gt;registerHook('Category'))
        return false;
    return true;
}</pre>
<p>Now, at the bottom of the file, create the hookCategory Function:</p>
<pre class="brush:php">public function hookCategory($params)
{
    global $cookie, $smarty;
    return $this-&gt;display(__FILE__, 'testing.tpl');
}</pre>
<p>&nbsp;</p>
<p>And that’s all!</p>
<p>Let’s install the module, go to a category page of the shop and see if the template’s content appears where we placed the hook variable. It’s likely we won’t see anything at the moment, but don’t fear. Since Prestashop uses caching, we must first re-compile the cache to see changes. Let’s go to <strong>preferences</strong>, then <strong>performance</strong> in back office, and turn on the option “<strong>Force Compile</strong>”, then refresh the category page. At this point, we should see a piece of text saying “Howdy guys! testing new hooks” If you don’t, since the Force Compile feature is a bit buggy, go to the Tools/Smarty/Compile folder and delete everything <strong>except the index.php</strong>. This should fix it, and you should be able to see the text.</p>
<h3>Conclusion</h3>
<p>We’re done! Thanks for reading. If you still have questions about how to create new hooks, feel free to contact me and I’ll be glad to help you.</p>
<h3>Additional Resources</h3>
<ul>
<li><a title="A list of Prestashop Hooks" href="http://doc.prestashop.com/display/PS15/Hooks+in+PrestaShop+1.5" target="_blank">A list of Prestashop Hooks</a></li>
<li><a title="EZ Hook Module: add new hooks in a couple of clicks" href="http://store.nemops.com/17-ez-hook.html" target="_blank">EZ Hook module: add new hooks in a couple of clicks</a></li>
</ul>
<p>The post <a rel="nofollow" href="http://nemops.com/a-deeper-look-at-prestashop-hooks/">A deeper look at Prestashop Hooks</a> appeared first on <a rel="nofollow" href="http://nemops.com">NemoPS</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://nemops.com/a-deeper-look-at-prestashop-hooks/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
