Notes

Getting started with Controllers

Edit on GitHub

OpenCart
4 minutes

Compatibility: OpenCart 2.x

  • Controllers are loaded based on the route
  • Every new controller must extend the Controller class
  • Controller names are based on the routes, and are written in PascalCase (aka UpperCamelCase), e.g. ControllerAccountRegister (ControllerFolderSubfolderFile)
  • 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 (folder/file), a default index() method is called. If the third part of a route (folder/file/method) 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

$this->foo->method()

You can view what you can do with this by looking into library/ files

1// e.g. $this->user (loaded from system/librarycart/user.php)
2
3$this->user->login($username, $password)
4$this->user->logout()
5$this->user->hasPermission($key, $value)
6$this->user->isLogged()
7$this->user->getId()
8$this->user->getUserName()
9$this->user->getGroupId()

Sample Controller.php

  1<?php
  2class ControllerAccountRegister extends Controller { // ContollerDirectorySubdirectory
  3	private $error = array();
  4
  5	public function index() { // index() function is required
  6		if ($this->customer->isLogged()) { // check if the customer is logged in
  7			$this->response->redirect($this->url->link('account/account', '', true)); // if not redirect to login page
  8		}
  9
 10		// LOAD LANGUAGE FILE
 11		$this->load->language('account/register');
 12
 13		// SET PAGE TITLE <title>
 14		$this->document->setTitle($this->language->get('heading_title'));
 15
 16		// ADD SCRIPTS & STYLESHEETS
 17		// These will be loaded in header.tpl as a foreach loop
 18		$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
 19		$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
 20		$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
 21
 22		// LOAD MODEL
 23		// When we load a model, we can use the methods defined in it
 24		$this->load->model('account/customer');
 25
 26		// Check if any data was POSTED
 27		// e.g. if login details were sent
 28		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
 29			$customer_id = $this->model_account_customer->addCustomer($this->request->post);
 30
 31			$this->customer->login($this->request->post['email'], $this->request->post['password']);
 32
 33			unset($this->session->data['guest']);
 34
 35			$this->response->redirect($this->url->link('account/success'));
 36		}
 37
 38		// BREADCRUMBS
 39		$data['breadcrumbs'] = array();
 40
 41		$data['breadcrumbs'][] = array(
 42			'text' => $this->language->get('text_home'),
 43			'href' => $this->url->link('common/home')
 44		);
 45
 46		$data['breadcrumbs'][] = array(
 47			'text' => $this->language->get('text_account'),
 48			'href' => $this->url->link('account/account', '', true)
 49		);
 50
 51		$data['breadcrumbs'][] = array(
 52			'text' => $this->language->get('text_register'),
 53			'href' => $this->url->link('account/register', '', true)
 54		);
 55		
 56		/* 
 57		SET LANGUAGE VARIABLES
 58
 59		These will be used in the template.tpl (e.g. <?php echo $heading_title ?>)
 60		*/
 61		$data['heading_title'] = $this->language->get('heading_title');
 62
 63		$data['button_continue'] = $this->language->get('button_continue');
 64		$data['button_upload'] = $this->language->get('button_upload');
 65
 66
 67		// See if there are any warning
 68		if (isset($this->error['warning'])) {
 69			$data['error_warning'] = $this->error['warning'];
 70		} else {
 71			$data['error_warning'] = '';
 72		}
 73		
 74		/* 
 75		URL saved as a variable which will be used in the template. 
 76		e.g. <form action="<?php $action; ?>">
 77		$this->url->link($route, $args = '', $secure = false)
 78		*/
 79		$data['action'] = $this->url->link('account/register', '', true); // the true at the end means load it over HTTPS
 80
 81		$data['customer_groups'] = array();
 82		
 83		
 84		if (isset($this->request->post['firstname'])) {
 85			$data['firstname'] = $this->request->post['firstname'];
 86		} else {
 87			$data['firstname'] = '';
 88		}	
 89
 90
 91		// LOAD OTHER CONTROLLERS
 92		$data['column_left'] = $this->load->controller('common/column_left');
 93		$data['column_right'] = $this->load->controller('common/column_right');
 94		$data['content_top'] = $this->load->controller('common/content_top');
 95		$data['content_bottom'] = $this->load->controller('common/content_bottom');
 96		$data['footer'] = $this->load->controller('common/footer');
 97		$data['header'] = $this->load->controller('common/header');
 98
 99		// LOAD A TEMPLATE.tpl file and pass it $data (i.e. everything you defined above with $data['key'])
100		$this->response->setOutput($this->load->view('account/register', $data));
101	}
102
103	// Sample function to send back a JSON response
104	public function sendData() {
105		// 1. Define an array
106		$json = array();
107			//
108			// code goes here
109			//
110
111		// 2. add data to that array
112		foreach ($custom_fields as $custom_field) {
113			$json[] = array(
114				'custom_field_id' => $custom_field['custom_field_id'],
115				'required'        => $custom_field['required']
116			);
117		}
118
119		// 3. send the array as a response
120		$this->response->addHeader('Content-Type: application/json');
121		$this->response->setOutput(json_encode($json));
122	}
123}