As a developer, it's always exciting to build custom stuff in any framework, and the same is true for OpenCart plugins as well.
In this two-part series, I'll explain custom plugin development in OpenCart. From the perspective of a newbie developer, we'll go through the details of extension development in OpenCart. We'll also create a small custom plugin to demonstrate each and every aspect of the OpenCart plugin structure.
In this first part, we'll build a custom plugin that displays recent products in the store front-end, and you'll be able to configure the number of products from the back-end itself. That's what the aim of this article is—develop a back-end plugin with a configuration form.
I assume that you've set up the latest version of OpenCart, which is 2.1.0.2 as of writing this. Before we go ahead and develop an actual plugin, I'll walk you through the basic plugin architecture of OpenCart in the very next section.
MVCL in a Nutshell
The OpenCart is developed with one of the most popular web development patterns, the MVC pattern, with a minor variation, or rather I would say it's an addition. The addition is in the form of a language component that makes it MVCL in the world of OpenCart. It could be that you've heard of this pattern, but for the sake of beginners, I'll quickly summarize what the pattern is all about.
The M in MVC stands for model, and that's where most of the business logic resides. In the context of OpenCart, it's the model that interacts with the database abstraction layer to do all the heavy lifting required to run the store. It's an area where you'll find yourself most of the time as a developer.
Next, the V stands for View, and it represents the presentation layer of the application. As the name suggests, it only deals with the presentation logic of any page, and it receives the input from other layers and generates the XHTML output most of the time. The business logic of an application should be kept away from this layer; it should only worry about what to do instead of how to do it.
It's the C, the controller, in MVC that sits in front of everything, handling every request and treating it accordingly. It's an area that includes most of the application logic, ranging from handling and validating user input to loading the proper model and view components to prepare the page output.
Finally, there's an additional component, L, which stands for language. It makes setting up multilingual sites a breeze.
So that's a quick view of the OpenCart architecture, and it'll make more sense as we move on to the in-depth explanation of each component.
The Skeleton of Any OpenCart Plugin
Let's have a quick look at the list of files that we need to implement for the custom back-end plugin.
-
admin/language/english/module/recent_products.php
: It's a file that holds static labels used throughout admin application area. -
admin/controller/module/recent_products.php
: It's a controller file that holds the application logic of our module. -
admin/view/template/module/recent_products.tpl
: It's a view template file and holds XHTML code.
In the next section, we'll create each file mentioned above, with an in-depth explanation.
As per the conventions, we need to place the custom plugin files under the module directory. In this case, as we're developing a back-end plugin, it'll be the directories under admin that hold our files. Of course, the files are spread across different directories, or rather components, as per the OpenCart architecture shown above.
Create Files for the Back-End Plugin
In this section, we'll start creating the module files. First, we'll create a language file admin/language/english/module/recent_products.php
with the following contents. It's an important file from the perspective of OpenCart, as it's a must for your plugin to be detected by OpenCart.
<?php // admin/language/english/module/recent_products.php // Heading $_['heading_title'] = 'Recent Products'; // Text $_['text_module'] = 'Modules'; $_['text_success'] = 'Success: You have modified Recent Products module!'; $_['text_edit'] = 'Edit Recent Products Module'; // Entry $_['entry_name'] = 'Module Name'; $_['entry_limit'] = 'Limit'; $_['entry_status'] = 'Status'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify Recent Products module!'; $_['error_name'] = 'Module Name must be between 3 and 64 characters!';
As you can see, we're assigning static labels to a PHP array. Later on, you'll have access to these variables in the view template file as the array is converted to PHP variables.
You may have also noticed that the file is created under the english directory as it's the default language of the store. Of course, in the case of a multilingual site, you'll need to make sure that you create it for other languages as well. For example, the French version of the same file should be created at admin/language/french/module/recent_products.php
.
Next, we'll create one of the most important plugin files—the controller file. Let's go ahead and create admin/controller/module/recent_products.php
with the following contents.
<?php // admin/controller/module/recent_products.php class ControllerModuleRecentProducts extends Controller { private $error = array(); public function index() { $this->load->language('module/recent_products'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('extension/module'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { if (!isset($this->request->get['module_id'])) { $this->model_extension_module->addModule('recent_products', $this->request->post); } else { $this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post); } $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL')); } $data['heading_title'] = $this->language->get('heading_title'); $data['text_edit'] = $this->language->get('text_edit'); $data['text_enabled'] = $this->language->get('text_enabled'); $data['text_disabled'] = $this->language->get('text_disabled'); $data['entry_name'] = $this->language->get('entry_name'); $data['entry_limit'] = $this->language->get('entry_limit'); $data['entry_status'] = $this->language->get('entry_status'); $data['button_save'] = $this->language->get('button_save'); $data['button_cancel'] = $this->language->get('button_cancel'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } if (isset($this->error['name'])) { $data['error_name'] = $this->error['name']; } else { $data['error_name'] = ''; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_module'), 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL') ); if (!isset($this->request->get['module_id'])) { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/recent_products', 'token=' . $this->session->data['token'], 'SSL') ); } else { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/recent_products', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], 'SSL') ); } if (!isset($this->request->get['module_id'])) { $data['action'] = $this->url->link('module/recent_products', 'token=' . $this->session->data['token'], 'SSL'); } else { $data['action'] = $this->url->link('module/recent_products', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], 'SSL'); } $data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'); if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $module_info = $this->model_extension_module->getModule($this->request->get['module_id']); } if (isset($this->request->post['name'])) { $data['name'] = $this->request->post['name']; } elseif (!empty($module_info)) { $data['name'] = $module_info['name']; } else { $data['name'] = ''; } if (isset($this->request->post['limit'])) { $data['limit'] = $this->request->post['limit']; } elseif (!empty($module_info)) { $data['limit'] = $module_info['limit']; } else { $data['limit'] = 5; } if (isset($this->request->post['status'])) { $data['status'] = $this->request->post['status']; } elseif (!empty($module_info)) { $data['status'] = $module_info['status']; } else { $data['status'] = ''; } $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('module/recent_products.tpl', $data)); } protected function validate() { if (!$this->user->hasPermission('modify', 'module/recent_products')) { $this->error['warning'] = $this->language->get('error_permission'); } if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 64)) { $this->error['name'] = $this->language->get('error_name'); } return !$this->error; } }
It defines the new class for our custom plugin that extends the base Controller
class. As per the conventions, the name of the class should mimic the directory structure under which the file is placed. So, the path controller/module/recent_products.php
is converted to ControllerModuleRecentProducts
by replacing the slash and underscore characters according to camel-case convention!
Next, there's a de-facto index
method that's called when the plugin is loaded in the front-end. So, it's an index method that defines most of the application logic of the plugin.
In the context of the current application, the shorthand $this->load->language
loads the corresponding language file. In our case, it loads the language file defined in the earlier section. The syntax is quite simple—you just need to pass the plugin name prefixed by module/
. The language variables can be accessed by the $this->language->get
method.
Next, it sets the page title by using the setTitle
method of the document object.
Moving ahead, the shorthand $this->load->model
is used to load the module model. It’s the model class that provides utility methods to save the module parameters and the like.
Following that, there’s an important snippet as shown below that checks if it’s POST data submission, and saves the module configuration in that case.
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { if (!isset($this->request->get['module_id'])) { $this->model_extension_module->addModule('recent_products', $this->request->post); } else { $this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post); } $this->session->data['success'] = $this->language->get('text_success'); $this->response->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL')); }
Further, we’re assigning language labels like heading_title
and text_edit
to the $data
array so that we can use them in the view template file.
Following that, there’s a snippet that builds the correct breadcrumb links for the configuration page.
$data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_module'), 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL') ); if (!isset($this->request->get['module_id'])) { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/recent_products', 'token=' . $this->session->data['token'], 'SSL') ); } else { $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/recent_products', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], 'SSL') ); }
Had the module already been configured earlier and in edit mode, the following snippet populates the default module configuration.
if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) { $module_info = $this->model_extension_module->getModule($this->request->get['module_id']); }
Finally, we’re loading the common page elements like header, footer and left sidebar. Also, it’s the $this->load->view
shorthand that loads the actual view file recent_products.tpl
and displays the configuration form.
There are a couple of important notes to remember in the controller file. You’ll see lots of calls like $this->load->ELEMENT
, where ELEMENT
could be view, model or language. It loads the corresponding view, model and language components.
The next and last file for today’s article is a view template file admin/view/template/module/recent_products.tpl
. Go ahead and create it!
<!-- admin/view/template/module/recent_products.tpl --> <?php echo $header; ?><?php echo $column_left; ?> <div id="content"> <div class="page-header"> <div class="container-fluid"> <div class="pull-right"> <button type="submit" form="form-recent-products" data-toggle="tooltip" title="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button> <a href="<?php echo $cancel; ?>" data-toggle="tooltip" title="<?php echo $button_cancel; ?>" class="btn btn-default"><i class="fa fa-reply"></i></a></div> <h1><?php echo $heading_title; ?></h1> <ul class="breadcrumb"> <?php foreach ($breadcrumbs as $breadcrumb) { ?> <li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li> <?php } ?> </ul> </div> </div> <div class="container-fluid"> <?php if ($error_warning) { ?> <div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?> <button type="button" class="close" data-dismiss="alert">×</button> </div> <?php } ?> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-pencil"></i> <?php echo $text_edit; ?></h3> </div> <div class="panel-body"> <form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-recent-products" class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label" for="input-name"><?php echo $entry_name; ?></label> <div class="col-sm-10"> <input type="text" name="name" value="<?php echo $name; ?>" placeholder="<?php echo $entry_name; ?>" id="input-name" class="form-control" /> <?php if ($error_name) { ?> <div class="text-danger"><?php echo $error_name; ?></div> <?php } ?> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="input-limit"><?php echo $entry_limit; ?></label> <div class="col-sm-10"> <input type="text" name="limit" value="<?php echo $limit; ?>" placeholder="<?php echo $entry_limit; ?>" id="input-limit" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for="input-status"><?php echo $entry_status; ?></label> <div class="col-sm-10"> <select name="status" id="input-status" class="form-control"> <?php if ($status) { ?> <option value="1" selected="selected"><?php echo $text_enabled; ?></option> <option value="0"><?php echo $text_disabled; ?></option> <?php } else { ?> <option value="1"><?php echo $text_enabled; ?></option> <option value="0" selected="selected"><?php echo $text_disabled; ?></option> <?php } ?> </select> </div> </div> </form> </div> </div> </div> </div> <?php echo $footer; ?>
Users with sharp eyes will already have noticed that it’s just displaying the variables that were passed from the controller file. Other than that, it’s simple XHTML code to display the configuration form, and the cherry on the top is that it’s responsive out of the box.
So, that’s it as far as the file setup is concerned for our back-end custom plugin.
Enable the Plugin
Head over to the back-end of OpenCart and navigate to Extensions > Modules. You should see Recent Products in the list. Click on the + sign to install the module as shown in the following screenshot.
Once it’s installed, you’ll see an edit icon. Click on that to open module configuration form.
In the configuration form, you could set the number of recent products you want to show in the front-end block. Also, don’t forget to set the status field to Enabled! Save the module, and it should look something like this.
There’s a new entry for the module titled Recent Products > My Recent Block Plugin. The reason is that you could replicate it multiple times for different pages!
So, we’re almost done! We’ve made a full-fledged back-end custom plugin in OpenCart. In the next part, we’ll go through the front-end counterpart of it that displays a nice-looking products block in the front-end!
Conclusion
Today, we’ve discussed custom plugin development in OpenCart. In the first part of this two-part series, we went through the back-end plugin development and created a working custom plugin that provides a configuration form.
If you're looking for additional OpenCart tools, utilities, extensions and so on that you can leverage in your own projects or for your own education, see what we have available in the marketplace.
In the next part, we’ll complete the plugin by creating the front-end part that displays product listings in the front-end. For any queries and feedback, please use the comment feed below.
Comments