Loading...

Advanced CS-Cart Add-on

We no longer maintain the Knowledge Base since version 4.3.x. All the latest user and developer documentation for 4.3.x and newer versions is now available at docs.cs-cart.com.

  • This article applies to CS-Cart versions:
  • 3.0.x

This tutorial demonstrates some advanced techniques in add-on writing like using hooks and postcontrollers.

Hooking is a very powerful technique, and we use it a lot in CS-Cart. PHP hooks can be used to perform additional pre- and post-processing of data, or to override default processing routines. TPL hooks are used to handle data on rendering, e.g. to display additional information with no need to modify the original template.

Postcontrollers (as well as precontrollers) are special PHP files of an add-on, which (depending on their names and location in the file structure of the add-on) are called before (or after) executing one or another standard controller.

In this tutorial we will create an add-on, which will demonstrate the usage of both PHP and TPL hooks.

The add-on will collect information about the categories being shown to a signed in user and store it in the database. This data will be then shown on the admin area home page as a table of users and according number of viewed categories.

Requirements

You will need an installed and functioning CS-Cart instance to be able to follow this tutorial. You can get a free 30-day trial version of CS-Cart on our site.

Basic knowledge of PHP, Smarty and CS-Cart add-on structure is required. It is recommended that you read the Add-on Folder Structure section of this documentation and follow the Basic CS-Cart Add-on tutorial before proceeding with this one.

Add-on Initialization: addon.xml, init.php

Go to the directory addons in your store installation root directory and create the folder advanced_addon. In this folder create the file addon.xml with the following content (download):

addons/advanced_addon/addon.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0"?>
<addon scheme="2.0">
	<id>advanced_addon</id>
	<name>Advanced Add-on</name>
	<description>Advanced Add-on</description>
	<version>1.0</version>
	<priority>100500</priority>
	<status>active</status>
 
	<!-- 
		Installation and uninstallation routines:
		initialize a database table to store data 
		and delete it on add-on uninstallation
	-->
	<queries>
		<item for="install">DROP TABLE IF EXISTS ?:test_addon_data;</item>
		<item for="install">
			CREATE TABLE `?:test_addon_data` (  
				`user_id` int(11) unsigned NOT NULL DEFAULT 0,  
				`categories` text NOT NULL DEFAULT '',
				PRIMARY KEY (`user_id`)
			) Engine=MyISAM DEFAULT CHARSET UTF8;
		</item>
		<item for="uninstall">DROP TABLE IF EXISTS ?:test_addon_data;</item>
	</queries>
</addon>
The addon.xml structure is described in the Add-on Scheme section, and a well-commented example of addon.xml can be found in the Appendix.

In the same directory create the file init.php with the following content (download):

addons/advanced_addon/init.php
1
2
3
4
5
6
7
8
9
<?php
 
if ( !defined('AREA') ) { die('Access denied'); }
 
fn_register_hooks(
	'get_category_data_pre'
);
 
?>
Function names are usually self-explanatory in CS-Cart (e.g. 'get_products' to get products). Hooks are normally named after the function they are placed in with '_pre' and '_post' for pre- and post-processing hooks accordingly (e.g. 'get_products_pre' and 'get_products_post').

In this file we declare that we are going to connect to the hook get_category_data_pre, which is called before getting category data by a certain query. You can find the information about this and other hooks in our Hook base.

Getting Data: func.php

In the add-on folder (addons/advanced_addon) create the file func.php. It will contain the actual function to be embedded to the hook (download):

addons/advanced_addon/func.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
 
if ( !defined('AREA') ) { die('Access denied'); }
 
function fn_advanced_addon_get_category_data_pre($category_id, $field_list, $get_main_pair, $skip_company_condition, $lang_code)
{
	//Getting authentication data to identify user
	$auth = $_SESSION['auth'];
 
	//Checking if the user is logged in and resides at the customer area
	if (!empty($auth['user_id']) && AREA == 'C') {
		//Checking if the database has data on the user.
		//Creating new record if necessary, using appending existing data if possible.
 
		$viewed_categories = db_get_field('SELECT categories FROM ?:test_addon_data WHERE user_id = ?i', $auth['user_id']);
 
		if (!empty($viewed_categories)) {
			$viewed_categories = unserialize($viewed_categories);
		}
 
		$viewed_categories[$category_id] = true;
		$viewed_categories = serialize($viewed_categories);
 
		db_query('REPLACE INTO ?:test_addon_data VALUES (?i, ?s)', $auth['user_id'], $viewed_categories);
	}
}
 
?>

The function fn_advanced_addon_get_category_data_pre will get the currently displayed categories and store this data to the database linked with the user id.

It is essential to follow the naming convention: 'fn_' + [addon id] + '_' + [hook name]. Any other function name will be ignored.

Showing Data in the Admin Area: extra.tpl, index.post.php

In order to show the collected data in the admin area we are going to use the TPL hook extra in the admin area home template (skins/basic/admin/views/index.tpl).

Go to the directory skins/basic/admin/addons and create a folder named advanced_addon. In this folder create a subfolder hooks and inside it another subfolder index. In this directory create the file extra.pre.tpl with the following content (download):

skins/basic/admin/addons/advanced_addon/hooks/index/extra.pre.tpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div class="statistics-box">
	<div class="statistics-body">
		<p class="strong">Viewed categories</p>
		<div class="clear">
			{if $viewed_categories}
				<ul>
					{foreach from=$viewed_categories item="category_data"}
						<li><strong><a href="{"profiles.update?user_id=`$category_data.user_id`"|fn_url}">{$category_data.user_name}</a></strong>:&nbsp;
							{foreach from=$category_data.categories key="category_id" item="category_name"}
								<a href="{"categories.update?category_id=`$category_id`"|fn_url}">{$category_name}</a>, 
							{/foreach}
						</li>
					{/foreach}
				</ul>
			{else}
				<ul>
					<li>No data found</li>
				</ul>
			{/if}
		</div>
	</div>
</div>
Unlike PHP hooks, TPL hooks should not be explicitly declared. It is sufficient to just place a specially named template in the specially named folder. The placing and naming convention is as follows: skins/[skin name]/[admin|customer]/addons/[addon id]/hooks/[template name]/[hook name].[pre|post].tpl.

The template can not gather data from the database itself, this is performed by a postcontroller for the index.php controller.

Go to the directory addons/advanced_addon and create the subdirectories controllers/admin. Switch to this directory and create the file index.post.php with the following content (download):

addons/advanced_addon/controllers/admin/index.post.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
if ( !defined('AREA') ) { die('Access denied'); }
 
$viewed_categories = db_get_array('SELECT * FROM ?:test_addon_data');
 
if (!empty($viewed_categories)) {
	foreach ($viewed_categories as $key => $category_data) {
		$category_data['user_name'] = fn_get_user_name($category_data['user_id']);
		$category_data['categories'] = unserialize($category_data['categories']);
		$category_data['categories']  = fn_get_category_name(array_keys($category_data['categories']));
 
		$viewed_categories[$key] = $category_data;
	}
 
	Registry::get('view')->assign('viewed_categories', $viewed_categories);
}
 
?>
Double check all the file paths, names and contents to guarantee that the add-on will work correctly.

Result

In order to see the add-on in action you will have to install it first. To do that go to Administration -> Add-ons in the admin area (that is by default on [your_domain]/admin.php). Find the item Advanced Add-on and click on Install in its row. You should see a successful installation notification.

Switch to the admin area home page and scroll down under the Latest orders section. You should see a section looking similar to this:

As you see, there are no data so far, but the section is shown properly.

Switch to the customer area, log in and surf a bit around the store. Just go over some random categories. You can also try several different accounts.

Refresh the home page of the admin area and check the state of the Viewed categories section:

The section should now indicate the categories you have just surfed through.

Home / Docs / Add-ons / Tutorials / Advanced CS-Cart Add-on