Quantcast
Channel: Envato Tuts+ Code
Viewing all articles
Browse latest Browse all 5160

From Beginner to Advanced OpenCart: More About MVC

$
0
0

Previously, we reviewed the Model-View-Controller - or MVC - architecture of OpenCart. In this regard, we created our first "Hello World!" Controller. So, In the last of the previous article, i just discussed some basic things of Controller. 

I hope you've practiced creating Controller as we're now taking ahead the discussion of controllers to the advanced level, but before starting the discussion let's get an overview what we're going to discuss in this article.

  1. Writing a real world controller
  2. Loading languages
  3. Loading and using libraries
  4. Libraries cheat sheet
  5. Creating a view
  6. Creating a model
  7. Model manipulation with a controller
  8. Conclusion

Writing a Real World Controller

We're going to create a simple user form following the OpenCart MVC Framework. For this, we need to create a controller first. As I've created a directory forms inside the catalog/controller

Note: Mac and Linux Users, don't forget to change your directory permission to 775.

Inside the forms directory, I've created a file myform.php . Now let's get started writing the code.

<?php
class ControllerFormsMyform extends Controller{ 

    public function index() 
	{
		$this->document->settitle('My Form'); // For setting the Page Title
		$this->data['breadcrumbs'] = array(); // Initialize a Breadcurmbs Array 
		$route = $this->request->get['route']; // Getting URL "route" by using GET Method
		// Making of Breadcrumb refering to home
		$this->data['breadcrumbs'][] = array(
			'text'      => 'Home',
			'href'      => $this->url->link('common/home'), // route path to home
			'separator' => false
		);
		// Making of Breadcrumb refering to current page
		$this->data['breadcrumbs'][] = array(
			'text'      => 'My Form',
			'href'      => $this->url->link($route), // route path to current url
			'separator' => '| ' //Breadcrumb seperating symbol
		);
		//End Breadcrumbs
		$this->data['form_heading'] = 'My Form Heading'; // Use $this->data keyword for parsing the controller data to view
		$this->data['first_value'] = 'Firstname: ';
		$this->data['second_value'] = 'Lastname: ';
		$this->data['third_value'] = 'Passport No.: ';
		$this->data['forth_value'] = 'Phone No.: ';
		$this->data['continue'] = $this->url->link('common/home'); // Link Data for continue button
		$this->data['button_continue'] = 'Continue'; // text data for continue page
		// Add Children of the Pages i.e., header,footer & columns
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);
		$this->template = 'default/template/forms/myform.tpl'; //Refer to the template / view file for User Interface
		$this->response->setoutput($this->render()); // Render the Template as Output
	}


}

?>

Review the code again and over again and try to create a controller like this. 

Loading the Languages

OpenCart gives an easy manipulation & playing with languages. So, in the above example, the hard-coded language texts were used. But it is recommended to use the text manipulation.

To load a language, use $this->language->load(route path of the language); & to get the specific language data use this syntax $this->language->get(language file data keyword); . 

Note that it is highly recommended to make a language file of each controller and page. The Language route path should also be same as controller.

 Loading and Using Libraries

There are a couple of precoded libraries available for the ease of the developer. Libraries can be located in /system/library . Libraries can be directly loaded into Controller by using the syntax: $this->library_name->method_name()

Previously, We've studied a few number of libraries, so you can manipulate them with your code. Some cheat sheet is available as following:

Cart Library

$this->cart->getProducts(); //Get All the Products available in Cart
$this->cart->add( $product_id, $qty = 1, $options = array()); // Add a Product to the Cart
$this->cart->remove( $key ); // Removes the Product from the Cart
$this->cart->clear(); // Empties the cart
$this->cart->getWeight(); // Returns sum of the weights of all products
$this->cart->getSubTotal(); // Returns the sub total of all products
$this->cart->getTotal() ; // Returns the Total of the Cart
$this->cart->countProducts() ; // Returns the number of products available in cart
$this->cart->hasProducts(); // Returns true if atleast one item is available in cart
$this->cart->hasStock(); // Returns false if atleast 1 product is out of stock in cart

Config Library

$this->config->get($key); //Returns setting by keyname based on application (catalog or admin)
$this->config->set($key, $value); // Set & override the setting value. (Dont save it in DB)
CURRENCY
$this->currency->set($currency); // Set & override the default currency code what is used in Session
$this->currency->format($number, $currency = '', $value = '', $format = TRUE); // Formats the Currency
$this->currency->convert($value, $from, $to); // Converts the currency value to another currency
$this->currency->getId(); // Gets the ID of Current Currency
$this->currency->getCode() ; // Returns the Currency Code of Current Currency
$this->currency->getValue($currency); // Returns the Exchange rate of Currency Provided
$this->currency->has(currency); // Returns true if available in currencies list

Customer Library

$this->customer->login($email, $password); // Logs in the Customer
$this->customer->logout(); // Logs out the Customer
$this->customer->isLogged(); // Returns true if User is logged int
$this->customer->getId(); //Returns the ID of current logged in user
$this->customer->getFirstName() // Returns the Firstname of logged in user
$this->customer->getLastName() // Returns the last name of logged in user
$this->customer->getEmail() ; // Returns the Email of logged in user
$this->customer->getTelephone() ; // Returns the Active user Telephone
$this->customer->getFax() ; // Returns the Fax Number of Active user
$this->customer->getNewsletter() ; // Returns the Newsletter statu
$this->customer->getCustomerGroupId() ; // Returns the Active Customer Group id

Database Library

$this->db->query($sql) // Executes the MySQL query & returns the rows count
$this->db->escape($value); // Cleans the Value and make it secure for Database
$this->db->getLastId($sql); //Returns Last Inserted id from more recent query

Document Library

$this->document->setTitle($title); //Sets Page Title
$this->document->getTitle(); // Gets the Page Title
$this->document->setDescription($description); //Sets page Description
$this->document->getDescription(); // Gets the page description
$this->document->setKeywords(); //Sets the Page Keywords
$this->document->getKeywords(); // Gets the Page Keywords
$this->document->addStyle( $href, $rel = 'stylesheet', $media = 'screen' ); // Add Style sheet to document
$this->document->getStyles(); // Gets page styles
$this->document->addScript( $script ); //Adds Script to page
$this->document->getScripts(); // Gets Page Scripts

Creating a View

In OpenCart, there are always templates what are used for views for displaying the output. In the above controller we've specified the view file location to theme/default/template/forms/myform.tpl.

Now, create a file with that name and place the code below:

<?php echo $header; ?><?php echo $column_left; ?><?php echo $column_right; ?><div id="content"><?php echo $content_top; ?><div class="breadcrumb"><?php foreach ($breadcrumbs as $breadcrumb) { ?><?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a><?php } ?></div><h1><?php echo $form_heading; ?></h1><div><form name="frm" method="POST" action=""><table  border="0"><tr><td width="30%"><?php echo $first_value;?></td><td width="70%"><input type="text" name="first_value" /></td></tr><tr><td ><?php echo $second_value;?></td><td ><input type="text" name="second_value" /></td></tr><tr><td ><?php echo $third_value;?></td><td ><input type="text" name="third_value" /></td></tr><tr><td ><?php echo $forth_value;?></td><td ><input type="text" name="forth_value" /></td></tr></table><div class="buttons"><div class="right"><input type="submit" class="button" value="<?php echo $button_continue; ?>" /></div></div></form></div><?php echo $content_bottom; ?></div><?php echo $footer; ?>

Creating a Model

A model holds the interaction with the database and its objects. So, before working on model, go to phpMyAdmin, select your store database (i.e., storedb) and execute this in SQL Panel

CREATE TABLE `oc_myforms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_value` varchar(80) DEFAULT NULL,
  `second_value` varchar(80) DEFAULT NULL,
  `third_value` varchar(80) DEFAULT NULL,
  `forth_value` varchar(80) DEFAULT NULL,
  `date_added` datetime DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

"oc" is a table prefix, use your own Store DB Prefix.

 Now, it is time to create your own Model. The purpose behind creating a Model to save the form data into the Database. so lets create our first model.

Create a new file myforms.php in catalog/model/forms/and place the code as below:

<?php
class ModelFormsMyform extends Model {
    public function saveData($data_array) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "myforms SET first_value='".$this->db->escape($data_array['first_value'])."' ,second_value='".$this->db->escape($data_array['second_value'])."',third_value='".$this->db->escape($data_array['third_value'])."',forth_value='".$this->db->escape($data_array['forth_value'])."',date_added=NOW() ");
		$form_id = $this->db->getLastId(); // Returns last inserted id
		return $form_id;
		}
}
?>

Model Manipulation with Controller

So, our final controller code will look like this:

<?php
class ControllerFormsMyform extends Controller{ 

    public function index() 
	{
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST')) {
		$this->load->model('forms/myform'); //route path without .php	
			$form_id = $this->model_forms_myform->saveData($this->request->post); //Parse all the posted data
			if($form_id)
			{
			$this->redirect($this->url->link('forms/myform')); //Reload the form again 	
			}
		}
		$this->document->settitle('My Form'); // For setting the Page Title
		$this->data['breadcrumbs'] = array(); // Initialize a Breadcurmbs Array 
		$route = $this->request->get['route']; // Getting URL "route" by using GET Method
		// Making of Breadcrumb refering to home
		$this->data['breadcrumbs'][] = array(
			'text'      => 'Home',
			'href'      => $this->url->link('common/home'), // route path to home
			'separator' => false
		);
		// Making of Breadcrumb refering to current page
		$this->data['breadcrumbs'][] = array(
			'text'      => 'My Form',
			'href'      => $this->url->link($route), // route path to current url
			'separator' => '| ' //Breadcrumb seperating symbol
		);
		//End Breadcrumbs
		$this->data['form_heading'] = 'My Form Heading'; // Use $this->data keyword for parsing the controller data to view
		$this->data['first_value'] = 'Firstname: ';
		$this->data['second_value'] = 'Lastname: ';
		$this->data['third_value'] = 'Passport No.: ';
		$this->data['forth_value'] = 'Phone No.: ';
		$this->data['continue'] = $this->url->link('common/home'); // Link Data for continue button
		$this->data['button_continue'] = 'Continue'; // text data for continue page
		// Add Children of the Pages i.e., header,footer & columns
		$this->children = array(
			'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header'
		);
		$this->template = 'default/template/forms/myform.tpl'; //Refer to the template / view file for User Interface
		$this->response->setoutput($this->render()); // Render the Template as Output
	}


}

?>

So, the condition will check if there is any data coming from POST method, if yes, then the database entry will be occured.

Note that you can add your validations and checks to validate the POST data.

Conclusion

Bingo! We have coded a real world Model-View-Controller application into OpenCart. You can explore more things and dive into the MVC sea; however, this was a basic introduction to MVC pattern and we've achieved our milestone.

In our future articles, we'll be discussing the modules and libraries creation of OpenCart. Please do provide your previous feedback on article in the comment feed below.


Viewing all articles
Browse latest Browse all 5160

Trending Articles