How to Become an Opencart Guru

How to become an OpenCart guru?

OpenCart 1.5.X developer quick start guide for beginners

This guide is written for developers already familiar with PHP, OOP and the MVC architecture

In the following, you'll see examples for the catalog side of the cart. The admin side is identical in function with the exception of the views which is noted in the relevant section


Understanding Libraries

All of the library functionality is accessible through Controller, Model and Views using $this->library_name. All of these can be found in the /system/library/ folder. For example, to access the current shopping cart's products, you'll need to use the Cart class, which is in /system/library/cart.php and can be accessed using $this->cart->getProducts()

Commonly used items

  • customer.php - Customer related functions
  • user.php - Admin user related functions
  • cart.php - Cart related functions
  • config.php - All settings are loaded from this
  • url.php - URL generation functions

Understanding the route parameter

OpenCart's framework relies on the route=aaa/bbb/ccc in the query string parameter to know what to load, and is the underpinning feature to finding the files you need to edit for each page. Most route's actually only use the aaa/bbb which should be seen as two parts, however some contain three parts aaa/bbb/ccc The first part aaa generally related to the folder within a generic folder such as the controller or template folders. The second part usually relates to the file name, without the relevant .php or .tpl extension. The third part is explained in the section "Understanding controllers" below


Understanding languages

Languages are stored in /catalog/language/ folder in the your-language subfolder. Within this, general text values used across various pages are stored in the your-language.php file inside the folder, so for the English language on the catalog side, you'll find the values in catalog/language/english/english.php. For specific page text, you'll need the route for the page (This is generally the case, but not always as you can specify any language file you like). For example, the search page has the route product/search, and therefore the language specific text for that page can be found in catalog/language/english/product/search.php (Notice the file's name and subfolder match the route followed by .php.

To load the language in a controller, you use

$this->language->load('product/search');

Then you can use the language library function get to retrieve specific language texts, such as

$some_variable = $this->language->get('heading_title');

The language variables are assigned in the language file using a special variable $_ which is an array of keys and text values. In your /catalog/language/english/product/search.php you should find something similar to

$_['heading_title']     = 'Search';

The values in the global language file english/english.php are automatically loaded and available to use without the $this->language->load method


Understanding controllers

Controllers are loaded based on the route and are fairly straight forward to understand. Controllers are located in the /catalog/controller/ folder. Continuing from the last example, the Controller for the Search page is in /product/search.php within this folder. Notice again that the route followed by .php is used.

Opening the controller file, you'll see a Pascal Case classname extending the Controller class, called ControllerProductSearch. This again is specific to the route, with Controller followed by the subfolder name and file name without the extension capitalised. The capitalisation is not actually required, but it's recommended for easy readability. It's worth noting that classnames don't take any values from the subfolder and file name other than letters and numbers. Underscores are removed.

Within the class are the methods. Methods in the class declared public are accessible to be run via the route - private are not. By default, with a standard two part route (aaa/bbb above), a default index() method is called. If the third part of a route (ccc above) is used, this method will be run instead. For example, account/return/insert will load the /catalog/controller/account/return.php file and class, and try to call the insert method


Understanding Models

Models in OpenCart are found in the /catalog/model/ folder and are grouped based on function, not route, and therefore you will need to load them in your controller via

$this->load->model('xxx/yyy');

This will load the file in the subfolder xxx called yyy.php. It is then available to use via the object

$this->model_xxx_yyy

and as with controllers, you can only call its public methods. For instance, to resize an image, you would use the tool/image model and call its resize method as follows

$this->load->model('tool/image');
$this->model_tool_image->resize('image.png', 300, 200);

Understanding variable assignment in views from the controller

In order to pass values to the view from the controller, you simply need to assign your data to the $this->data variable, which is essentially an array of key => value pairs. As an example

$this->data['example_var'] = 123;

Accessing this in a view is a little should be easy to understand if you're familiar with the extract() method which converts each key into a variable. So the example_var key becomes $example_var and can be accessed as such in the view.


Understanding themes

Themes are available to the catalog side only, and are basically a folder of templates, stylesheets and theme images. Theme folders are placed in the /catalog/view/theme/ folder followed by the theme name. The folder name isn't of importance with exception to the default folder

The admin side uses /admin/view/template/ (skipping the /theme/theme-name/ from the path as it doesn't allow differing themes)

Template files reside in a template folder within the theme folder. Should any template not be available for the currently selected theme, the default folder's template is used instead as a fallback. This means themes can be created with very few files and still function fully. It also reduces code duplication and issues as upgrades are made


Understanding views (templates)

As with language and models, the view file's are generally related to the route, though don't have to be at all. Templates on the catalog side are usually found in /catalog/view/theme/your-theme/template/ unless it doesn't exist, in which case the default theme's templates will be used. For our search page example above, the file is product/search.tpl. For routes with three parts, it is generally in aaa/bbb_ccc.tpl though there's no hard set rule. In the admin, most pages follow this, with the exception that pages listing items, like the product listing page, are in catalog/product_list.tpl and the product editing form is in catalog/product_form.tpl. Again, these aren't set, but a standard for the default cart.

The template file is in fact just another php file, but with a .tpl extension and is actually run in the controller file, therefore all of the things you can code in a controller can be run in a template file (though not recommended unless absolutely necessary)


Understanding the database object

Queries are run using

$result = $this->db->query("SELECT * FROM `" . DB_PREFIX . "table`");

DB_PREFIX as the name suggests is a constant containing the database prefix if one exists

$result will return an object for SELECT queries, containing a few properties

$result->row contains the first row's data if one or more are returned as an associative array

$result->rows contains an array of row results, ideal for looping over using foreach

$result->num_rows contains the number of results returned

There are also a few extra methods the $this->db object has

$this->db->escape() uses mysql_real_escape_string() on the value passed

$this->db->countAffected returns the number of rows affected by an UPDATE query and so on

$this->db->getLastId() returns the last auto increment id using mysql_insert_id()


Understanding reserved variables

OpenCart has predefined variables to use in place of the standard $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUEST AND $_SERVER

$_SESSION is edited using $this->session->data where data is an associative array mimicking the $_SESSION

All of the others can be accessed using $this->request and have been "cleaned" to comply with magic quotes enabled/disabled, so

$_GET becomes $this->request->get

$_POST becomes $this->request->post

$_COOKIE becomes $this->request->cookie

$_FILES becomes $this->request->files

$_REQUEST becomes $this->request->request

$_SERVER becomes $this->request->server


Summary

While the above isn't a bulletproof guide for developers, hopefully it will serve as a good starting point for those getting started

Opencart module needed : electronic transactions

If you'd like to have a quick start guide for OpenCart development, you can check out my article here. As for vQmod changing drastically, I can assure you that it won't (unlike opencart's somewhat hectic changes between even minor versions). vQmod is authored by myself and Qphoria and is backward compatible right to version 1.0

To do what you've suggested, the simplest thing to me would still be to use a payment gateway if that's what you're developing rather than a module. They are essentially the same thing, just in a different area of OpenCart's admin and folder structure so it makes little difference how you do it, just more aesthetically pleasing. If your payment gateway requires data passed via a POST then check out the PayPal Standard files on how to do this - if it's via cURL then check out the PayPal Pro files

Where to find good documentation on extending Opencart

Official documentation
http://docs.opencart.com/developer/module/

Unofficial help
http://opencart.hostjars.com/blog/3 and http://opencart.hostjars.com/blog/34

Opencart 2.x - show featured module if category is empty

If exists an extension or mod to do this

I never heard of such an extension and I don't think that there extensions of this type (anyway, have a look at the extensions store)

If not, the way to get there is enough

Basically we will work with two files:

Category controller file:<OC_ROOT>/catalog/controller/product/category.php

Category view file:<OC_ROOT>/catalog/view/theme/xxx/template/product/category.tpl

We just need to:

(1) Determine to load the module or not (In the controller)

Using a simple if statement, you can check if the # of products in the current category equals zero, then you can proceed with constructing the module, luckily we already have the # of products in that line:
$product_total = $this->model_catalog_product->getTotalProducts($filter_data);

so you just need to check if $product_total == 0

(2) Construct the module HTML in a proper way (In the controller)

If you opened any controller, you will notice that there is a line always used to execute some controller and return it's output as a string, this line is:

$this->load->controller('controller route')

you can even notice it in the same file:

$data['column_left'] = $this->load->controller('common/column_left');

so you just need to copy that line and use it to load the module that you want (using the module route which is module/featured for your case), however, some modules in OC expect some parameters to be passed to the index() function and won't work without it, don't panic :D, you just need to open any file that makes use of modules (such as common/column_left.php) and do the same, I copied it for you (with slight modification):

if ($this->config->get($module_code . '_status')) 
{
$data['module_html'] = $this->load->controller('module/' . $module_code);
}
else
{
$this->load->model('extension/module');
$setting_info = $this->model_extension_module->getModule($module_id);
if ($setting_info)
{
$data['module_html'] = $this->load->controller('module/' . $module_code, $setting_info);
}
}


the values of $module_id and $module_code can be found in the table <DB_PREFIX>_module, for your case they will be:

$module_id = 28;
$module_code = 'featured';

(3) Display the module in the page (In the view)

Just check if the value of $module_html is set, then display it in the container div



P.S: This artice is very good and provides an excellent base to develop code for open cart 1.5.x, it can also be used for OC 2.x with little modification, Good Luck!

opencart how to add manufacturers list like categories list

category.tpl is the template for the category controller. Its purpose is to show categories. Try to direct your browser to the http://your.site/index.php?route=product/manufacturer and you will get list of manufacturers. The template is /catalog/view/theme/default/template/product/manufacturer_list.tpl.

Your error is a result of one simple thing: the $manufacturers variable is not defined in ControllerModuleCategory controller (aka category.php). If you want use a variable in a template, you must define it in a relevant controller.

In order to obtain list of manufacturers exactly in the /catalog/view/theme/default/template/module/category.tpl (even if it isn't the purpose of this module), you need be done with few things:

1) In the /catalog/model/catalog/manufacturer.php file (model ModelCatalogManufacturer) add function (this function will help you to obtain the list of manufacturers from the database):

public function getManufacturerByCategory($category_id) {
$query = $this->db->query("SELECT m.*
FROM " . DB_PREFIX . "product p
RIGHT JOIN " . DB_PREFIX . "product_to_category p2c ON
p.product_id = p2c.product_id
LEFT JOIN " . DB_PREFIX . "manufacturer m ON
p.manufacturer_id = m.manufacturer_id
WHERE
p2c.category_id = " . (int)$category_id . " AND
m.manufacturer_id IS NOT NULL
GROUP BY m.manufacturer_id");
return $query->rows;
}

2) In the /catalog/controller/module/category.php file (aka ControllerModuleCategory controller), prior to if (file_exists(DIR_TEMPLATE . $this->config->get('confi... insert the code:

if (isset($this->request->get['path'])) {
$category_id = array_pop($parts);

$this->load->model('catalog/manufacturer');
$this->data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturerByCategory($category_id);
} else {
$this->data['manufacturers'] = array();
}

(Keep in mind $this->data['manufacturers'] from the controller will be available in the template as $manufacturers. $this->data['categories'] will be $categories, $this->data['another_var'] will be $another_var and so on.)

And since the moment you can use your foreach ($manufacturers as $manufacturer) in the category module template (the place where you did try the foreach, when you've received "Undefined variable" error) in order to output list of manufacturers which are applied to products from current category.

Best way is create another module, "manufacturer" module, instead of illegitimate using of category module. But I'm not sure that right now you are ready for this challenge.

BTW, I'm all for shadyyx's link to the Jay Gilford's guide. It is awesome quick start guide for beginners.



Related Topics



Leave a reply



Submit