How to become an OpenCart guru?

PhpOpencart

Php Problem Overview


It seems like they have no documentation except some api calls on their official forums. I have experience with Zend framework and CodeIgniter framework. Can any OpenCart masters recommend me the best way to learn it and master in shortest amount of time? I have to do a big project with it soon.

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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']	

Solution 3 - Php

There is a OpenCart Wiki website with documentation for beginner developers. Follow the urls given below for more details:

http://wiki.opencarthelp.com/doku.php?id=start</strike>
http://wiki.opencarthelp.com/doku.php?id=methods_reference</strike>

INTERNET ARCHIVE links

http://web.archive.org/web/20160305131349/http://wiki.opencarthelp.com/doku.php?id=start http://web.archive.org/web/20160305131349/http://wiki.opencarthelp.com/doku.php?id=methods_reference

E.g. Method reference has details for :

  1. Customer Login
  2. DB Access
  3. Shopping Cart Handling
  4. Config
  5. Cache
  6. Currency Handling

Still There are some pages under construction but it is going to be helpful.

[Update]

As of Jan-2018, opencarhelp.com domain is down.

Solution 4 - Php

Although this topic has been answered many times already, I would like to offer another approach to mastering OpenCart based on my experience.

Learning by doing

By creating your own OpenCart framework from scratch with a handful of files you can understand how everything is put together. I will be mimicking the file structure of OpenCart for you.

Create a file index.php

<?php
// My simpleCart

1. Registry

Opencart uses the Registry pattern to list all instances of loaded classes. It is the heart of your OpenCart app. The registry object is then passed around to every category, model, and library for quick access to other objects.

create a file with path /system/engine/registry.php

<?php
// Registry class. 
class Registry
{
    private $data = array();

    public function set($key, $value){
        $this->data[$key] = $value;
    }

    public function get($key){
        return (isset($this->data[$key])) ? $this->data[$key] : false;
    }
}

in your index.php

<?php
// My simpleCart

//load dependency files
require_once('system/engine/registry.php');

//initialize registry
$registry = new Registry;

2. Output

Now let's add an output which will be our HTML in the future. After all, the whole idea is to send a string of text to the browser.

Create file system/library/response.php

<?php
class Response {
    private $output;

    public function getOutput() {
        return $this->output;
    }
    
    public function setOutput($output) {
        $this->output = $output;
    }

    public function output() {
        if ($this->output) {
            echo $this->output;
        }
    }
}

and in your index.php

<?php
// My simpleCart

//load dependency files
require_once('system/engine/registry.php');
require_once('system/library/response.php');

//initialize registry
$registry = new Registry;

//initialize response
$response = new Response;
//add response object to the registry
$registry->set('response', $response);

//lets set an output as a test
$registry->get('response')->setOutput('Hello World');

//send the output to the client
$registry->get('response')->output();

> Notice I added Hello world only as an example. We will remove it further on. Refresh your site to check it. The browser should display Hello World.

3. Controllers

Think of Controllers as pages. They will define what will be displayed to the client: text, html, json, download or even an image. For now, we just want a page that sends text.

We will create a controller for the home page.

add a file with path catalog/controller/common/home.php

<?php

class ControllerCommonHome{

    private $registry = array();

    public function __construct($registry){
        $this->registry = $registry;
    }

    public function index(){

        $output = 'Home Page';
        //using the registry to get the response object and set the Output
        $this->registry->get('response')->setOutput($output);
    }
}

and edit your index.php

<?php
// My simpleCart

//load registry
require_once('system/engine/registry.php');
//load response
require_once('system/library/response.php');

//initialize registry
$registry = new Registry;

//initialize response
$response = new Response;
//add resoinse object to the registry
$registry->set('response', $response);

//load controller common/home
require_once('catalog/controller/common/home.php');
$controller = new ControllerCommonHome($registry);
$controller->index();

//send the output to the client
$registry->get('response')->output();

> notice how I passed the $refistry to the ControllerCommonHome so that I could access it inside the controller.

4. Router

We don't want controllers to be hardcoded, right. We will use a parameter route from the url address to tell our cart which controller to load.

Create a file with path system/library/request.php

<?php
class Request {
    public $get = array();
    
    //for now I just need the $_GET parameter
    public function __construct() {
        $this->get = $_GET;
    }
}

Create the Router class that will be responsible for initializing the Controller file based on the route (in other words: dynamically call the controller)

<?php
class Router {
    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function dispatch($route) {
        require_once('catalog/controller/'.$route.'.php');
        $class = "Controller".str_replace('/', '', $route);
        $controller = new $class($this->registry);
        $controller->index();
    }
}

load it into your index.php

<?php
require_once('system/engine/registry.php');
require_once('system/engine/router.php');
require_once('system/library/response.php');
require_once('system/library/request.php');

$registry = new Registry;

$response = new Response;
$registry->set('response', $response);

$request = new Request;
$registry->set('request', $request);

//get the route from the url
if(isset($registry->get('request')->get['route'])){
    $route = $registry->get('request')->get['route'];
}else{
    $route = 'common/home';
}

//initiate the router and dispatch it base on the route
$router = new Router($registry);
$router->dispatch($route);


$registry->get('response')->output();

> Notice how I load everything into the $registry and then pass it to the $router which then passes it to the $controller.

This post is already too long, but I hope it will give a basic understanding of the MVC pattern in OpenCart.

> If you want me to continue with this post and tell you how other things work like models and views, rate this answer so that I know.

Also check out my Youtube https://www.youtube.com/dreamvention and my blog https://dreamvention.com/blog I will be posting more tips and tutorials there for you guys!

Solution 5 - Php

PHP is a fairly large language with over 5000 built-in functions so one strategy for learning a new platform is to identify which functions it uses most frequently and spend some time getting to know those very well.

I've run some queries on the OpenCart source code and the top 10 most commonly used functions are:

array()
count()
explode()
implode()
mktime()
delete()
time()
date()
sprintf()
list()

All 52 listed here as well as Linux bash commands you can use on any codebase to identify commonly used functions: https://www.antropy.co.uk/blog/efficient-learning-for-new-opencart-developers/

Solution 6 - Php

This youtube videos playlist can also be helpful to become OpenCart developer Gurus:

OpenCart Videos Tutorials

  1. Introduction and Table of Contents This video goes through the introduction of the series

  2. OpenCart installation localhost This video go through the OpenCart installation in localhost

  3. Files and folder structure of Opencart It describes files and folders structure of OpenCart

  4. Creating Database Table schema in OpenCart It shows database table schema and shows how to create database tables in OpenCart

  5. OpenCart Library Predefined Objects’ Methods It describes OpenCart Library Predefined Objects’ Methods and shows where to find them.

  6. MVCL pattern, code flow and request & response in OpenCart It shows MVCL pattern, code flow and request & response in OpenCart. They describe the flow as in the picture below: MVCL described with Code

  7. Install, Configure and Uninstall Opencart module It shows three ways to upload modules, then install, configure and uninstall the OpenCart 3 module/extension.

  8. Layouts and position in Opencart 3 It describes the OpenCart 3 layouts and positions. It shows how to show customize layouts for different pages, giving examples of categories pages. We show the different layout for a different category.

  9. Event overview of Opencart You will learn what Events are in OpenCart, how they work and what makes them so useful.

  10. Opencart API documentation for developer This video will show how to use and make custom opencart API

Once you see these videos then you can start coding :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodeCrackView Question on Stackoverflow
Solution 1 - PhpJay GilfordView Answer on Stackoverflow
Solution 2 - PhpAbdul RehmanView Answer on Stackoverflow
Solution 3 - PhpDharmangView Answer on Stackoverflow
Solution 4 - PhpDmitriy ZhukView Answer on Stackoverflow
Solution 5 - PhpPaul FeakinsView Answer on Stackoverflow
Solution 6 - PhpRupak NepaliView Answer on Stackoverflow