How to become an OpenCart guru?

Global Library Methods : Basic opencart library functions along with their functionalities, Most of these can be called from anywhere in the catalog or admin folders (controllers, models, views)

CACHE
$this->cache->delete($key) - Deletes cache [product, category, country, zone, language, currency,
manufacturer]

CART
$this->cart->getProducts() Gets all products currently in the cart including options, discounted prices, etc.
$this->cart->add( $product_id, $qty = 1, $options = array()) - Allows you to add a product to the cart
$this->cart->remove( $key ) - Allows you to remove a product from the cart
$this->cart->clear() - Allows you to remove all products from the cart
$this->cart->getWeight() - Sum of the weight of all products in the cart that have require shipping set to Yes
$this->cart->getSubTotal() - returns the subtotal of all products added together before tax
$this->cart->getTotal() - returns the total of all products added together after tax
$this->cart->countProducts() - returns the count of all product in the cart
$this->cart->hasProducts() - returns true if there is at least one item in the cart
$this->cart->hasStock() - returns false if there is at least one item in the cart that is out of stock
$this->cart->hasShipping() - returns true if there is at least one item in the cart that requires shipping
$this->cart->hasDownload() - returns true if there is at least one item in the cart that has a download
associated

CONFIG
$this->config->get($key) - returns setting value by keyname based on application (catalog or admin)
$this->config->set($key, $value) - set the value to override the setting value. DOES NOT SAVE TO DATABASE

CURRENCY
$this->currency->set($currency) - set or override the currency code to be used in the session
$this->currency->format($number, $currency = '', $value = '', $format = TRUE) - format the currency
$this->currency->convert($value, $from, $to) - convert a value from one currency to another. Currencies must
exist
$this->currency->getId() - get the database entry id for the current currency (1, 2, 3, 4)
$this->currency->getCode() - get the 3-letter iso code for the current currency (USD, EUR, GBP, AUD, etc)
$this->currency->getValue($currency) - get the current exchange rate from the database for the specified
currency.
$this->currency->has(currency) - Check if a currency exists in the opencart currency list

CUSTOMER
$this->customer->login($email, $password) - Log a customer in
$this->customer->logout() - Log a customer out
$this->customer->isLogged() - check if customer is logged in
$this->customer->getId() - get the database entry id for the current customer (integer)
$this->customer->getFirstName() - get customer first name
$this->customer->getLastName() - get customer last name
$this->customer->getEmail() - get customer email
$this->customer->getTelephone() - get customer telephone number
$this->customer->getFax() - get customer fax number
$this->customer->getNewsletter() - get customer newsletter status
$this->customer->getCustomerGroupId() - get customer group id
$this->customer->getAddressId() - get customer default address id (maps to the address database field)

DATABASE
$this->db->query($sql) - Execute the specified sql statement. Returns row data and rowcount.
$this->db->escape($value) - Escape/clean data before entering it into database
$this->db->countAffected($sql) - Returns count of affected rows from most recent query execution
$this->db->getLastId($sql) - Returns last auto-increment id from more recent query execution 4

DOCUMENT (*Called from controller only before renderer)
$this->document->setTitle($title) - Set page title
$this->document->getTitle()- Get page title
$this->document->setDescription($description) - Set meta description
$this->document->getDescription()- Get meta description
$this->document->setKeywords()- Set meta keywords
$this->document->getKeywords()- Get meta keywords
$this->document->setBase($base) - Set page base
$this->document->getBase() - Get page base
$this->document->setCharset($charset) - Set page charset
$this->document->getCharset() - Get page charset
$this->document->setLanguage($language) - Set page language
$this->document->getLanguage()- Get page language
$this->document->setDirection($direction) - Set page direction (rtl/ltr)
$this->document->getDirection()- Get page direction (rtl/ltr)
$this->document->addLink( $href, $rel ) – Add dynamic <link> tag
$this->document->getLinks()- Get page link tags
$this->document->addStyle( $href, $rel = 'stylesheet', $media = 'screen' ) – Add dynamic style
$this->document->getStyles()- Get page styles
$this->document->addScript( $script ) - Add dynamic script
$this->document->getScripts()- Get page scripts
$this->document->addBreadcrumb($text, $href, $separator = ' &gt; ') – Add breadcrumb
$this->document->getBreadcrumbs()- Get Breadcrumbs

ENCRYPT
$this->encryption->encrypt($value) - Encrypt data based on key in admin settings
$this->encryption->decrypt($value) - Decrypt data based on key in admin settings

IMAGE
$this->image->resize($width = 0, $height = 0)

JSON
$this->json->encode( $data )
$this->json->decode( $data , $assoc = FALSE)

LANGUAGE
$this->language->load($filename);

LENGTH
$this->length->convert($value, $from, $to) - convert a length to another. units must exist
$this->length->format($value, $unit, $decimal_point = '.', $thousand_point = ',') - format the length to use
unit

LOG
$this->log->write($message) - Writes to the system error log

REQUEST
$this->request->clean($data) - Cleans the data coming in to prevent XSS
$this->request->get['x'] - Same as $_GET['x']
$this->request->post['x'] - Same as $_POST['x']

RESPONSE
$this->response->addHeader($header) - additional php header tags can be defined here
$this->response->redirect($url) - redirects to the url specified

TAX
$this->tax->setZone($country_id, $zone_id) - Set the country and zone id for taxing (integer)
$this->tax->calculate($value, $tax_class_id, $calculate = TRUE) - Calculate all taxes to be added to the total
$this->tax->getRate($tax_class_id) - Get the rates of a tax class id
$this->tax->getDescription($tax_class_id) - Get the description of a tax class id
$this->tax->has($tax_class_id) - Check if a tax class id exists in opencart

SESSION
$this->session->data['x'] - Same as $_SESSION['x']  

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

Tags:

Php

Opencart