Magento: Create Custom Module

Today, We are going learn to create custom module in Magento, so here are the below steps to create a sample ‘Helloworld’ module-

New Custom Module Creator for Magento2

Sample file structure:

[root]\app\code\local\{Namespace}\{Modulename}
[root]\app\code\local\{Namespace}\{Modulename}\controllers
[root]\app\code\local\{Namespace}\{Modulename}\etc
[root]\app\code\local\{Namespace}\{Modulename}\etc\config.xml
[root]\app\code\local\{Namespace}\{Modulename}\Helper
[root]\app\code\local\{Namespace}\{Modulename}\Model
[root]\app\code\local\{Namespace}\{Modulename}\{Modulename}.php

{Namespace} is a user defined variable. Basically it’s just a mechanism that allows the user to create disparate classes that would otherwise have the same names.

{Modulename} this is the name of your module.

controllers is where all the controllers go.

Model holds all of the models for your module.

For example we use “A2bizz” as namespace and “Helloworld” as Module. we entirely sure if it matters or not, but as a general rule we always capitalize the first letter and leave the rest lower case.

Step One

Inform Magento that you have a custom module. Note the file locations (need to create directories as necessary).

app/etc/modules/A2bizz_HelloWorld.xml

<?xml version=”1.0″?>
<config>
	<modules>
		<A2bizz_HelloWorld>
			<active>true</active>
			<codePool>local</codePool>
		</A2bizz_HelloWorld>
	</modules>
</config>

In this way we have informed Magento that we have an active module (you can turn it off from here by setting ‘active’ to false. we have also informed Magento that it is located in the ‘local’ code pool.

Step Two

Configure your new module. Note the file locations (need to create directories as necessary).

app/code/local/A2bizz/HelloWorld/etc/config.xml

<?xml version=”1.0″?>
<config>
	<global>
		<modules>
			<a2bizz_helloworld>
				<version>0.1.0</version>
			</a2bizz_helloworld>
		</modules>
		<blocks>
			<helloworld>
				<rewrite>
					<helloworld>A2bizz_HelloWorld_Block_HelloWorld</helloworld>
				</rewrite>
			</helloworld>
		</blocks>
	</global>
	<frontend>
		<routers>
			<helloworld>
				<use>standard</use>
				<args>
					<module>A2bizz_HelloWorld</module>
					<frontName>helloworld</frontName>
				</args>
			</helloworld>
		</routers>
		<layout>
			<updates>
				<helloworld>
					<file>helloworld.xml</file>
				</helloworld>
			</updates>
		</layout>
	</frontend>
</config>

Here we informed Magento of module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).

We aware Magento that module contains block files which are found in A2bizz/HelloWorld/Block. Here class name will have A2bizz_HelloWorld_Block. If you want to see the many possibilities of stuff that goes in here, check out Magento config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there.

Step Three

Here is my block code. It doesn’t really do anything, but shows some functionality.

app/code/local/A2bizz/HelloWorld/Block/HelloWorld.php

<?php
class A2bizz_HelloWorld_Block_HelloWorld extends Mage_Core_Block_Template
{
	public function _prepareLayout()
	{
		$this->getLayout()->getBlock(‘breadcrumbs’)
			->addCrumb(‘home’, array(‘label’=>Mage::helper(‘catalogsearch’)->__(‘Home’),
						‘title’=>Mage::helper(‘catalogsearch’)->__(‘Go to Home Page’),
						‘link’=>Mage::getBaseUrl())
						)
			->addCrumb(‘customer’, 
						array(‘label’=>Mage::helper(‘customer’)->__(‘Foo’))
						);
		return parent::_prepareLayout();
	}

	public function myMessage(){
		return “This is A2bizz, This is our module.”;
	}
}
?>

Step Four

Now we create a template file (.phtml) file.

app/design/frontend/default/default/template/helloworld/helloworld.phtml

<?php

echo ‘Hello World ! This A2bizz’;
echo “<BR/>”;
echo $this->myMessage();

?>

Now, Our custom module has been created you can use it, for additional functionality.

Magento2: create custom module

Today we will learn to create custom module in magento2-

For installation and initial learning please visit our previous blogs of magento2.

The overall development we are doing on Ubuntu 14.4, local environment the base directory structure of my local is –
/var/www/html/magento2/app/code/A2bizz/Blog

You can download full code from GIT below given URL –
https://github.com/bloga2bizz/Magento2-Sample-Frontend-Module

customModule

Step 1.Initialization of your custom module –

First of all we will have to initialize our custom module to the list of modules with magento configuration, for which we will have to first create a /var/www/html/magento2/app/code/A2bizz/Blog/registration.php file and write below code –

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'A2bizz_Blog',
__DIR__
);

?>

if you hit your magento2 URL i.e. http://localhost/magento2/, now you will get below issue –

Cannot read contents from file "/var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml"

Now create module.xml on file /var/www/html/magento2/app/code/A2bizz/Blog/etc/module.xml and write below code –

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="A2bizz_Blog" setup_version="2.0.0" />
</config>

Now we have initialised our custom module, To check that please check /var/www/html/magento2/app/etc/config.php where your created module will be listed down, if not then upgrade custom module.

Step 2. creating controller & routing –

Now Further create controller file /var/www/html/magento2/app/code/A2bizz/Blog/Controller/Index/Index.php

<?php

namespace A2bizz\Blog\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{    
	protected $resultPageFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $resultPageFactory
	)
	{
		$this->resultPageFactory = $resultPageFactory;
		parent::__construct($context);
	}
    
    public function execute()
    {
        return $this->resultPageFactory->create();
    }

}

and a routes.xml file on path /var/www/html/magento2/app/code/A2bizz/Blog/etc/frontend/routes.xml,which will provide the path execution to your custom module –

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="blog" frontName="blog">
            <module name="A2bizz_Blog" />
        </route>
    </router>
</config>

here, in this xml we initializing the calling path for our custom module. In this way we have successfully hit out the controller for our custom module. Here in our example hit – http://127.0.0.1/magento2/blog

if the hitting above URL is showing blank white page, it means controller is hitted in a proper manner and now asking for the page layout.

Step 3. designing layout (view) for our custom module –

Now Further create layout files for your custom module /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/layout/blog_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="A2bizz\Blog\Block\Blog" name="blog" template="A2bizz_Blog::blog.phtml" />
        </referenceContainer>
    </body>
</page>

and add /var/www/html/magento2/app/code/A2bizz/Blog/view/frontend/templates/blog.phtml

<?php
echo "Blog Template";
?>

Now hit your custom module URL again, will show you below error
Object DOMDocument should be created.

it means it is unable to find corresponding Block method for its layout.

Now create your Block method, in /var/www/html/magento2/app/code/A2bizz/Blog/Block/Blog.php

<?php
namespace A2bizz\Blog\Block;

class Blog extends \Magento\Framework\View\Element\Template
{
	public function _prepareLayout()
	{
	    return parent::_prepareLayout();
	}
}
?>

Now, Executing your URL http://localhost/magento2/blog, will show you complete module functionality.

Magento2: Overriding Block

This post go through the process to extend a block in Magento2.

There are a few steps to override a Magento2 block as given below –

Step 1. Building a Magento 2 extension structure

Building directories as following:

magento2 --- app --- code
                       |--- A2bizz --- Sample
                                             | --- Block
                                             | --- etc
                                                    | --- module.xml
                                                    | --- di.xml

Creating module.xml to define a Magento2 extension:

<?xml version="1.0"?>
<!--
/**
 * Created by blog.a2bizz@gmail.com
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="A2bizz_Sample" setup_version="0.0.1"/>
</config>

Step 2. Setting preference in di.xml

Creating di.xml to refer the overriding block class:

<?xml version="1.0"?> 
<!-- /** * Created by blog.a2bizz@gmail.com */ --> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> 
<preference for="Magento\Theme\Block\Html\Title" type="A2bizz\Sample\Block\HelloTitle" /> 
</config> 

A2bizz\Sample\Block\HelloTitle will be used to override Magento\Theme\Block\Html\Title.

Step 3. Defining an overriding class

Under magento2/app/code/A2bizz/Sample/Block, defining HelloTitle.php as following.

<?php
/**
 * Created by blog.a2bizz@gmail.com
 */
namespace A2bizz\Sample\Block;
use Magento\Framework\View\Element\Template;
class HelloTitle extends \Magento\Theme\Block\Html\Title
{
    public function getPageTitle()
    {
        return 'A2bizz Custom';
    }
    protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Theme\Block\Html\Title'));
        return parent::_toHtml();
    }
}

HelloTitle.php redefines function getPageTitle() to override the function in \Magento\Theme\Block\Html\Title. The new getPageTitle() just return a text string, but it may also implements a complex logic.

HelloTitle.php also redefines function _toHtml(). Although HelloTitle overrides \Magento\Theme\Block\Html\Title, the template file of \Magento\Theme\Block\Html\Title is still supposed to be used. And the real path of a template file is determined by both the module name of a block and the template attribute of the block. Therefore, the module name of HelloTitle is still Magento_Theme, rather than A2bizz_Sample.

This line

$this->setModuleName($this->extractModuleName('Magento\Theme\Block\Html\Title'));

sets the correct nominal module name. This module name is necessary to render with the template originally defined for Magento\Theme\Block\Html\Title.

Fix ‘Namespace_Module_Helper_Data’ not found fatal error in Magento ?

Following are the steps to resolve”fatal error: Class ‘Namespace_Module_Helper_Data’ not found” error.

  1. Install the extension when compilation is disabled in Magento admin.
  2. To check whether compilation is enabled or disabled, go to
    Admin > system >Tools > compilation  check enabled / disabled
  3. If enabled, then disable it and install the extension. Once the extension is installed you can enable compilation again by using ‘Re-run Compilation.
  4. If you have already installed the extension & are facing the above error, Disable the extension from app/etc/modules/Namespace_Module.xml
  5. <active>true</active> 
    To
    <active>false</active>
  6. Clear cache from var/cache folder.
  7. Now you will have the access to Magento admin panel from where you can disable the compilation.
  8. Now enable the extension from Namespace_Module.xml
  9. <active>false</active>
    To
    <active>true</active>
  10. Clear cache from var/cache folder.

Magento2 : adding menu in admin section of custom module

As we already know of Structure of a custom module in Magento2, lets begin with creating Menu for our custom module in Admin section, in magento2 the management of a menu section is totally controlled by menu.xml file which exists inside etc/adminhtml directory –

Let for example you have a following directory path of a custom module  –

 magento2/app/code/A2bizz/Blog/

Where A2bizz is the name of namespace and Blog is the name of our custom module, now inside this structure we will have a etc folder which is again have two directories, adminhtml and frontend.

magento2/app/code/A2bizz/Blog/etc/adminhtml/menu.xml

a sample of menu.xml is given below –

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
	<add id="A2bizz_Blog::blog" title="Designer" module="A2bizz_Blog" sortOrder="0" resource="A2bizz_Blog::blog"/>
        <add id="A2bizz_Blog::blog_page" title="Pages" module="A2bizz_Blog" sortOrder="0" parent="A2bizz_Blog::blog" action="blog/page" resource="A2bizz_Blog::page"/>
    </menu>
</config>

Magento2: Registration of module

For Registering our custom module, we need to create a php file named registration.php in the root of our custom folder and write the below given code

\Magento\Framework\Component\ComponentRegistrar::register(
     \Magento\Framework\Component\ComponentRegistrar::MODULE,
     '_',
     __DIR__
 );

if examine this code then you will see that after the name of module there is a __DIR__ variable which is a php variable to identify the current working directory, it means that you can register your module from any where in Root of magento directory.

Enjoy this Article, don’t miss to comment us or write us if you need to know more about magento2

Open Cart Tutorial

 

Introduction to MVC-L

 

OpenCart is an excellent platform for developers looking to understand PHP web frameworks in general. It is one of the easiest to follow MVC structured applications available. OpenCart allows you to learn the MVC framework while giving you access to the familiar PHP, mySQL and HTML technologies on which it is built. This guide will assume a basic understanding of HTML, CSS, Javascript, PHP (including classes and inheritance), and mySQL, and will describe how these are used in the OpenCart system.

MVC(L)

OpenCart is designed to follow an MVC design pattern. The components of MVC (Model View Controller) can be broken down as follows.

M - Model
This is where you will interact directly with your database, pulling data out and restructuring it to a format that is suitable for your frontend. This will usually mainly consist of DB queries, and little more. If you are used to writing mySQL queries, you will enjoy the way OpenCart provides access to continue to do just that. OpenCart does not use an ORM, but allows you to write direct database queries.

V - View
This is the display side of the MVC pattern. The idea of the M and C is to pull as much logic out of the view as possible, meaning simpler templates. In order to redesign your whole store, you simply modify the View component, the M, C and L would remain the same. The view files in OpenCart have the .tpl suffix.

C - Controller
This is where you will pull together the data from the Model, any config settings saved with your install or modules, and then render it by choosing the appropriate View file(s).

L - Language
OpenCart extends MVC to MVCL, providing an easy way of separating language specific information for internationalization. You can use language files to store any text like headings, titles, button text, etc., so that you only need to adjust one file per language to provide translations of your store.

Directory structure
The OpenCart directory structure is based around two important parts of the OpenCart application.
The frontend and the admin interface are each represented by a folder in the top level of your OpenCart installation. The frontend folder is called catalog/ and the admin folder is called admin/. If you are making modifications only to the admin of an OpenCart store, you should not expect to modify any file within the catalog/ folder. If you are working on the frontend only, you should not be modifying the admin/ folder at all.
Within each of the admin/ and catalog/ folders, you will find a folder for each of the Model, View, Controller and Language components of the OpenCart application.
Several other folders exist in your OpenCart installation.
The system folder contains classes and functions used by both the admin and catalog areas of your store. Within this folder are email helpers, database helpers, the core definition of controllers, models and other parts of the OpenCart engine and library classes. When modifying OpenCart functionality, you will seldom need to edit any of the system files.
The image folder contains all the images that are uploaded via the Image manager. These are your product images, additional images, and the cached versions of images that OpenCart has resized.
The download folder contains any downloads associated with products. Downloads are given a hashed suffix to avoid malicious users guessing the filenames correctly and accessing your downloads directly. This is why you will see random strings on the end of your download filenames in this directory.

 

Developing modules

 

Writing OpenCart modules can be a very good way to learn how the fundamentals of OpenCart actually work. Just as the rest of OpenCart, modules follow the MVCL design pattern. This documentation guide will describe how you use each of the MVC-L components to create the admin and frontend parts of your module. The easiest way to create a module is to download the DIY Module Builder skeleton from HostJars. This module contains the directory structure, files, and instructions on how to understand and build your own modules. This page is a more theoretical guide.

Basic directory structure
The basic file structure for your module will be divided into two sections, the admin and the catalog folders. The contents of each folder will follow the MVC-L framework respectively, with the difference that the admin will deal solely with backend functionality, and the catalog with frontend functionality. Users of your module will interact and configure its settings in the administration side of the store. Therefore, the files in the admin folder will handle any changes to its settings, the way the module is displayed in the administration, install/uninstalling the module, etc. Likewise, the way the module is displayed and how it works in the front end of the store will be handled by the files in the catalog folder.

The image above displays a skeleton of the directory structure that your module should follow. A good way to get started with your module is to duplicate the folder structure and create the files above. What will go in those files is determined by what your module is trying to accomplish, but the basic functionality is detailed in the sections below.

Admin module functionality
When a store owner uses your module, they will want to edit the module’s configuration options in the admin in order to decide which layouts to display the module on, whether it is enabled or disabled, and any module specific options. As the module developer, you will need to create the admin page where the module may be edited and the configuration options added or adjusted.
All admin files are located in the admin/ folder. You will find four folders within the admin/ folder:

  1. controller
  2. view
  3. language
  4. model

All modules will require at least a single file in each of the view and controller folders. Most will require a file in each of the model and language folders. Usually the files have the same name, except the view file has a different suffix (.tpl). We will go through these files one by one.

Controller

The first file you make will be the controller for your module’s admin interface page. OpenCart identifies existing modules automatically, simply by reading the admin/controller/module folder of your store. Any modules existing in this folder will automatically be shown on the Modules page, and on the User Permissions, page. You may call your controller file my_module.php.
The controller file is the place where you can load the language files to convert text into variables to be utilized in the template file. In the diagram above, you can see the $_[‘text’] variable being handled by the controller, then sent as $text to the view. You will also utilize multiple model files and their class functions here, including your module’s model file if it has one. For more information on loading files see Loading files in the controller.
You may also have a function defined as public function install(). This function will be triggered when the install link is clicked on the Extensions > Modules page. Similarly, a function defined as public function uninstall() will be triggered when the uninstall link is clicked. You can use these functions to create and remove any structures (such as database tables or config settings) required by your module. It is good practice to create an uninstall function to clean up any changes your module has made. To see the specific code for an install(), uninstall(), visit Install/Uninstall a module.

Accessed via URL

The controller is the only file in the MVC-L framework to be accessed by URL in OpenCart. In the administration, the URL will look like /admin/index.php?route=module/my_module&token. The admin adds a token to the URL, whereas the link in the catalog will not have it. As a result, the controller file will have a function defined as public function index(). This is a publicly accessible ‘page’ that is loaded by the URL, which will be shown when the Edit button is clicked, and where the view form will submit to. The submitted data will be processed in this function and saved to the `settings` database table through the controller’s config object.

View
The second required file for your module’s admin interface is the view file. This will be created in the admin/view/template/module folder, and will have the suffix .tpl. This is standard for OpenCart view files. In this file you will create a form for the user to fill out and submit. It will be submitted to the module controller’s index function. The easiest way to create your view file is to copy and paste an existing, similar view file, and edit the form to contain the correct fields for your module’s configuration options. You may call your view file my_module.tpl.
In the view, you will be able to access the text from the language that the controller file stored as a PHP variable. See Loading Files in the Controller for the code on how to do so.

Model

It is uncommon for modules to require a model file on the admin side. However, if your module relies on its own database table, or a custom query to create data of a particular format, then you may find yourself writing a model file. An example of this may be if you are writing a visitor counter module, where each visitor is stored in a database table with their IP address and number of visits. You may then create a model file, with a function to define and create this extra table in the OpenCart database. The model file will live in the admin/model/module folder. You may call your model file my_module.php, the same as your controller and language files.

Frontend module functionality

The frontend of your module follows the same pattern as the admin interface just described. What you will include in each of your frontend files will largely depend on what your module is supposed to do. A module can access any model files that already exist in OpenCart, you do not need to write your own database queries if the same query already exists. For example, the catalog/product model contains many useful queries for fetching products. Using these model functions should be preferred over reinventing the wheel.
A key difference in the frontend of your module, is that your view file will be in the catalog/view/theme//template/module folder. This is a significantly deeper folder structure to the admin view file because of themes.
On the frontend part of your module you will have access to the configuration options saved by your module, through both the controller’s config object, and the $settings variable passed to the module controller’s index function. You can control aspects of the frontend display on the basis of these settings.

 

Install/Uninstall a module

 

It is recommended that developers include an install and uninstall function for their modules in the controller file. Within these functions we will need to load the necessary model files for a clean install/uninstall. To learn how to load a file in the controller, see Loading files in the controller.

Install:

The first thing we will include within the install function, are calls to any functions from the model where tables are created in the db. Secondly, we will want to enable the module for OpenCart with the install. Therefore, install function should loosely follow the code below:

public function install() {
       $this->load->model('module/my_module');
       $this->model_feed_my_module->createTable(); 
       $this->load->model('setting/setting');
       $this->model_setting_setting->editSetting('my_module', array('my_module_status'=>1));
   }

Uninstall:

The uninstall function should loosely follow the code below:

public function uninstall() {
        $this->load->model('module/my_module');
        $this->model_feed_my_module->deleteTable();
         
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('my_module', array('my_module_status'=>0));
    }

If we created a table in the db from a function in the model for the install, we will need to load another function from the model that removes the table when uninstalled. Also, we will want to disable the status of the module when uninstalled.

 

Developing new product feeds

 

OpenCart includes several useful Product Feeds in the core, but you may find you require a custom format and decide to create your own. Writing OpenCart product feeds is very similar to writing OpenCart modules, and can be a very good way to learn how the fundamentals of OpenCart actually work. Just as the rest of OpenCart, feeds follow the MVCL design pattern. This documentation guide will describe how you use each of the MVCL components to create the admin and frontend parts of your product feed.

Admin feed functionality

When a store owner uses your product feed, they will want to edit the product feed’s configuration options in the admin in order to select whether it is enabled or disabled and any specific options you make available. As the developer, you will need to create the admin page where the product feed may be edited.
All admin files are located in the admin/ folder. You will find four folders within the admin/ folder:

  1. controller
  2. view
  3. language
  4. model

All product feeds will require at least a single file in each of the view and controller folders. Some will require a file in each of the model and language folders. Usually the files have the same name, except the view file has a different suffix (.tpl). We will go through these files one by one.

Controller

The first file you make will be the controller for your product feed’s admin interface page. OpenCart identifies existing product feeds automatically, simply by reading the admin/controller/feeds folder of your store. Any product feed files existing in this folder will automatically be shown on the Product Feeds page, and on the User Permissions, page. You may call your controller file my_feed.php.
The controller file will have a function defined as public function index(). This is a publicly accessible ‘page’, which will be shown when the Edit button is clicked, and where the view form will submit to. The submitted data will be processed in this function and saved to the `settings` database table through the controller’s config object.
You may also have a function defined as public function install(). This function will be triggered when the install link is clicked on the Extensions > feeds page. Similarly, a function defined as public function uninstall() will be triggered when the uninstall link is clicked. You can use these functions to create and remove any structures (such as database tables or config settings) required by your feed. It is good practice to create an uninstall function to clean up any changes your feed has made.

View

The second required file for your feed’s admin interface is the view file. This will be created in the admin/view/template/feed folder, and will have the suffix .tpl. This is standard for OpenCart view files. In this file you will create a form for the user to fill out and submit. It will be submitted to the feed controller’s index function. The easiest way to create your view file is to copy and paste an existing, similar view file, and edit the form to contain the correct fields for your feed’s configuration options. You may call your view file my_feed.tpl.

Language

The third file you will usually create for any feed is the language file(s). You will need Cheap AC Milan football shirts one language file per language that your feed is compatible with. The language file will live in the admin/language//feed folder. It simply contains a PHP associative array called $_, which contains the internal name as the key and the translation as the value. You may call your language file my_feed.php, the same as your controller and model files.

Model

It is uncommon for feeds to require a model file on the admin side. However, if your feed relies on its own database table, or a custom query to create data of a particular format, then you may find yourself writing a model file. An example of this may be if you are writing a visitor counter feed, where each visitor is stored in a database table with their IP address and number of visits. You may then create a model file, with a function to define and create this extra table in the OpenCart database. The model file will live in the admin/model/feed folder. You may call your model file my_feed.php, the same as your controller and language files.

Frontend feed functionality

The frontend of your feed follows the same pattern as the admin interface just described. What you will include in each of your frontend files will largely depend on what your feed is supposed to do. A feed can access any model files that already exist in OpenCart, you do not need to write your own database queries if the same query already exists. For example, the catalog/product model contains many useful queries for fetching products. Using these model functions should be preferred over reinventing the wheel.
A key difference in the frontend of your feed, is that your view file will be in the catalog/view/theme//template/feed folder. This is a significantly deeper folder structure to the admin view file because of themes. An OpenCart store may have many different frontend themes available, but only one admin template.
On the frontend part of your feed you will have access to the configuration options saved by your feed, through both the controller’s config object, and the $settings variable passed to the feed controller’s index function. You can control aspects of the frontend display on the basis of these settings.

 

Loading files in the controller

 

In OpenCart’s MVC-L framework, your module’s controller is the glue connecting your the language, model, and template files to each other. The controller is responsible for grabbing the text contained in the language file and making them accessible as PHP variables in Cheap Barcelona football shirts the view’s template file. In addition to inheriting the functions available in the controller’s parent class, Controller, you can also load any of OpenCart’s default model files and their functions in the controller. In this documentation, we will show the PHP code needed to load language and model files and their functions.

Loading the language file

The controller brings the text stored in the language file, and turns them into variables that can be echoed in the template file to displayed text. This is especially useful for managing translations of your module. Instead of modifying your .tpl file every time you have a new translation to change each piece of text inside, you just need to modify the text in your language file, and the variables will remain the same in the controller and the template.
The piece of code below will load the language file inside in your module’s controller. Inside the parentheses you will need to include the path to the language file from inside the language folder.

$this->load->language('module/my_module');

It is important to remember that the admin controller will only load the admin language file, but not the catalog language file; and likewise the catalog controller will only load the catalog language file. Once the language file is loaded into the controller, you can store its text into a php variable with the use of the $data array. The $this->language->get('text') will grab the text from the $_['text'] variable inside of the language file.

// for opencart version below than 2.x.x.x
$this->data['text'] = $this->language->get('text');

//for opencart version 2.x.x.x + 
$data['text'] = $this->language->get('text');

The $this->language->get(‘text’) will grab the text from the $_[‘text’] variable inside of the language file we just loaded above. Every element of the data array will be converted into its own variable. The $data[‘text’] will become $text for the template file inside view. The $text variable can be echoed in the view’s .tpl file wherever needed:

<?php echo $text; ?>

Setting the heading title

The following code will set text from the language file as the heading title of the page:

$this->document->setTitle($this->language->get('heading_title'));

This will grab the text for the variable $_['heading_title'] stored in the module’s language file.
If you need the text to be stored as a php session variable, use $this->session->data['text'] instead of $this->data['text'] or $data['text'].

Loading model files

Loading model files into your controller file will allow your module to utilize OpenCart’s built-in functions. The functions inside the model files interact with the store’s database and to add/pull important information for your module. We recommended that you to take advantage of these functions, rather than making your own DB queries. Take some time to explore the model folders in both the admin and catalog files, to see which files may benefit cheap football shirts your module’s purpose. For example, if your module needs to pull product information from the store’s database, it will be useful to load the admin/model/catalog/products.php file, since it already has a multitude of helpful, built-in functions that interact with the store’s products in the database.
Your module can load any model file its controller file using the following code, granted that they are in the same admin or catalog folder as the controller.

$this->load->model('setting/setting');

You will need to specify the path to the file you want to load from the admin cheap football tops folder within the parentheses. The code above will load the settings class so we have access to the functions within the ModelSettingSetting class in our model’s controller file. Use the following format in your code to call a function from a loaded model file:

$this->model_setting_setting->editSetting('my_module', $this->request->post);

The underscores refer to the file designations for model/setting/setting.php. If you have a model file included for your module your code would follow the format mentioned above, since the model file is uploaded to model folder.

$this->load->model(module/my_module.php);
$this->model_module_my_module->myFunction();

The code above will load the my_module.php stored in admin/model/module/my_module.php.
Instead of using spaces in file names for your module, use underscores.

Loading template files
In the controller you will need to load your module’s template file in view. To do so, set $this->template or $data['template'] as so:

$this->template = 'module/my_module.tpl';
or
$data['template'] = 'module/my_module.tpl';

Loading library files

The OpenCart directory contains a collection of library files that can be cheap football kits accessed by both the admin and catalog controller files. These files are located under system/library in the root folder of the OpenCart store. In the code examples seen in loading the language file, both $this->load->language and $this->document give access to functions within the language.php and document.php files in the library folder. If you want to access a function in a library file you need to call it using $this->[insert library file name]->function() in the controller class.

cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap France football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |
cheap football shirts  |

Opencart 2.x.x Event System Tutorial

Overview

OpenCart 2.x introduces a number of new features for the module developers and one of them is the event system. This is going to be a quick tutorial teaching you how to make use of it in your modules.

The concept is simple, yet very effective. It allows you to write code which will get executed when something interesting happens in OpenCart. Like when an order is made, or a customer is created without the need of using vQmod or OCMOD. By using the events system, you can avoid collisions which happen when you are using a modification system like vQmod or OCMOD. Additionally since you write the event handlers in PHP file, you get to enjoy proper code coloring/completion/linting from your editor/IDE.

Basics

Use of events involves only two steps:

  1. Register an event handler
  2. Implement the event handler

The event handlers are simply methods defined in controller files. You can use one file for all your methods or you can create separate controller for your event handlers. To register your event handlers you need to use the extension/event model (OpenCart 2.0.1+) or the tool/event model for OpenCart 2.0.0.0. The extension/event model has 2 methods: addEvent($code, $trigger, $action) and deleteEvent($code). As you can guess the addEvent() method is used to register event handlers and the deleteEvent() is used to unregister event handlers. It is a good practice to register your event handlers in the install() method of your module’s controller in the admin/ directory. It is also advised to unregister your event handlers when your module is being uninstalled, which can be done in the uninstall() method of the same controller file.

The $code argument is used to group your event handlers. It is a good idea to set this to the name of your module, much like you have named your main controller file.

The $trigger argument is the event name which you would like to set your handler to. A list of all available triggers can be found here: https://github.com/opencart/opencart/wiki/Events-(script-notifications).

The $action argument is the route to your handler function. It is written in the form of a standard route to a controller. For example module/a2bizz/on_user_created.

Example

Steps of implementing an event handler with simple code examples are given below.

The example assumes that we are working with OpenCart 2.0.1+. Now let’s assume that we are creating a module called “a2bizz”. The admin controller file for the module will be admin/controller/module/a2bizz.php. The catalog controller file for the module will be catalog/controller/module/a2bizz.php.

The module will achieve 2 simple tasks – send e-mail messages to the administrator when a store is deleted and upon a customer registration. The triggers that we are going to use are pre.admin.store.delete and post.customer.add.

First we will register our event handlers in the install() method of our module:

public function install() {
    $this->load->model('extension/event');
    $this->model_extension_event->addEvent('a2bizz', 'pre.admin.store.delete', 'module/mymodule/on_store_delete');
    $this->model_extension_event->addEvent('a2bizz', 'post.customer.add', 'module/mymodule/on_customer_add');
}

Uninstall process like this:

public function uninstall() {
    $this->load->model('extension/event');
    $this->model_extension_event->deleteEvent('a2bizz');
}

Next, we need to implement the event handlers. The pre.admin.store.delete event is emitted in the admin area, so its handler must be implemented in the admin controller file for our module. We would like our event handler method to notify the administrator that a store Cheap Manchester United football shirts has been deleted. Events starting with pre are emitted before the action is executed, and events starting with post are executed after the action has been taken. We would also like to include the store domain in our message, which is why we have chosen the “pre” event instead of the “post”. If we register for the post.admin.store.delete event, we will not be able to read the store’s domain.

Our event handler should look something like this:

public function on_store_delete($store_id) {
    $this->load->model('setting/store');
    $store_info = $this->model_setting_store->getStore($store_id);
    $admin_mail = $this->config->get('config_email');
    mail($admin_mail, "A store has been deleted", "The store " . $store_info['url'] . " was deleted.");
}

All that is left now is to implement the handler method for the post.customer.add event. We will do this in the catalog controller of our module. The method will notify the administrator when a new customer is registered. The method should look similar to this:

public function on_customer_add($customer_id) {
    $this->load->model('account/customer');
    $customer_info = $this->model_account_customer->getCustomer($customer_id);
    $admin_mail = $this->config->get('config_email');
    mail($admin_mail, "New Customer", "A new customer has just registered with the following e-mail: " . $customer_info['email']);
}

Note: We are using the mail() function for sending e-mails for simplicity. In a real module you need to use OpenCart’s Mail class for sending e-mails.

That’s it! Our module is ready to rock. The final cheap football shirts versions of our files is as follows:

admin/controller/module/a2bizz.php

<?php class ControllerModuleA2bizz extends Controller { public function install() { $this->load->model('extension/event');
        $this->model_extension_event->addEvent('a2bizz', 'pre.admin.store.delete', 'module/a2bizz/on_store_delete');
        $this->model_extension_event->addEvent('a2bizz', 'post.customer.add', 'module/a2bizz/on_customer_add');
    }
    
    public function uninstall() {
        $this->load->model('extension/event');
        $this->model_extension_event->deleteEvent('a2bizz');
    }
    
    public function on_store_delete($store_id) {
        $this->load->model('setting/store');
        $store_info = $this->model_setting_store->getStore($store_id);
        $admin_mail = $this->config->get('config_email');
        mail($admin_mail, "A store has been deleted", "The store " . $store_info['url'] . " was deleted.");
    }
}

catalog/controller/module/a2bizz.php

<?php class ControllerModuleA2bizz extends Controller { public function on_customer_add($customer_id) { $this->load->model('account/customer');
        $customer_info = $this->model_account_customer->getCustomer($customer_id);
        $admin_mail = $this->config->get('config_email');
        mail($admin_mail, "New Customer", "A new customer has just registered with the following e-mail: " . $customer_info['email']);
    }
}

Apart from the standard use, the event system can be used to create cross-module integrations. Using the Event object ($this->event), you can trigger any event at any point. You can use it to trigger your own events as well. Imagine that you cheap football kits are developing a module for customer comments. You can trigger events on a comment post, for example. This will allow other module developers to create handler methods for your events and execute code without the need of vQmod or OCMOD. This will ensure better system stability and better customer experience. You can also use the system to register and trigger your own cheap football tops events at runtime.

cheap Barcelona football shirts  |
cheap Real Madrid football shirts  |
cheap Manchester United football shirts  |
cheap England football shirts  |
cheap AC Milan football shirts  |
cheap Inter Milan football shirts  |
cheap Liverpool footbal lshirts  |
cheap France football shirts  |
cheap Juventus football shirts  |
cheap Celtic football shirts  |
cheap Celtic football shirts  |
cheap Italy football shirts  |
cheap Inter Milan football shirts  |
cheap Barcelona football shirts  |
cheap Chelsea football kits  |
cheap Arsenal football kits  |
cheap Liverpool football shirts  |
cheap Real Madrid football shirts  |
cheap Portugal football shirts  |
cheap Belgium football shirts  |
cheap Barcelona football shirts  |
cheap France football shirts  |
cheap Germany football shirts  |
cheap North Ireland football shirts  |
cheap Juventus football shirts  |
cheap AC Milan football shirts  |
cheap Manchester United football shirts  |
cheap Italy football shirts  |
cheap Manchester United football shirts  |
cheap Real Madrid football shirts  |
cheap Real Madrid football shirts  |
cheap Chelsea football shirts  |
cheap Germany football shirts  |