OpenCart – How Arrays are Used

This article is for those that are interested in the programming language PHP and how OpenCart makes good use of arrays, one of many different elements in PHP. Since a huge portion of how data is gathered, saved, and iterated in the Opencart MVC has to do with arrays this is what we will be looking at today.

WHAT IS AN ARRAY?

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. Arrays are enormously powerful in their ability to hold virtually any type of data. Array’s can even be stored in a MYSQL database table and retrieved later on for use (with structure in tact).

A basic array:
$array = array(
"foo" => "bar",
"bar" => "foo",
);

In the array above you will see the keys as well as the values. FOO is a key and BAR is it’s value. In PHP you can easily iterate through that array in a few ways but by far the most common would be to use the for each()

foreach($array as $key => $value){
echo “Key = “.$key. ” AND VALUE = ” . $value;
}

As far as Opencart is concerned we are just going to pick one of the many areas where arrays are used.

THE SHOPPING CART ARRAY

Let’s imagine that we have pressed the ADD TO CART BUTON, contacted the control by means of using AJAX and passed validation, we must now contact the core system file found in system/library/cart.php Above you saw the call for $this->cart->add($this->request->post['product_id'], $quantity, $option); This is looking for a function that will be explained below.

Before I go on further to explain how this function works we need to discuss what has already happened LONG before you ever pressed the add to cart button. In a nutshell, all items along with their options are stored in a session variable. This session is started when you reach the store for the first time and does not die until you either close your browser (in which case it might still survive depending upon your browser settings) OR if you clean your cache, and lastly if you complete a checkout entirely. If you scroll to the top of system/library/cart.php you will see the following code:

if (!isset($this->session->data['cart']) || !is_array($this->session->data['cart'])) {
$this->session->data['cart'] = array();
}

This very simply states that, IF NO CART SESSION EXISTS OR IF CART SESSION IS NOT ARRAY, CREATE ONE. The array will remain empty until you start adding items.

Continuing on with the ADD function. The function looks like this:

public function add($product_id, $qty = 1, $option = array()) {
if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ‘:’ . base64_encode(serialize($option));
}
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}$this->data = array();
}

In red I highlighted the arguments being passed to the function by the control. The arguments in the control look like this: $this->cart->add($this->request->post['product_id'], $quantity, $option) Passing arguments is a nifty way to distribute data from one function to the next and in this case we are dealing with the product_id, quantity, and options (if any). Let’s look closely at the first part of the function:

if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ‘:’ . base64_encode(serialize($option));
}

What you are seeing is: IF NO OPTION(s) variable $key = $product_id }ELSE{ variable $key = STRING. This string is very important; it holds the product_id and the entire option array, concatenated together by a ‘:’. You will notice the $option variable is base64_encode(serialize(). Why do this? This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean. Likewise, the serialize function is designed to keep array’s intact so you can use them again later.

And now the last part of this function:

if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}$this->data = array();

And here is the function with comments to explain what is happening:

if ((int)$qty && ((int)$qty > 0)) {

//validation that quantity is greater than 0 and correct form

if (!isset($this->session->data['cart'][$key])) {

//if the product DOESN’T exist in cart with matching properties/options. We are using the variable $key to run the check

$this->session->data['cart'][$key] = (int)$qty;

//add product to cart array (new product)

} else {

$this->session->data['cart'][$key] += (int)$qty;

//this is if product DOES exist in cart with matching properties/options //Add another of the same to change quantity. This is done by (+=)
}
}

In short, we add a new item to the cart array if it doesn’t already exist OR we increase the quantity of an existing item because the system has detected an identical match with the same options/properties. If you remember that we started with the session array: $this->session->data['cart'] as an empty array. Now we are filling the array with a KEY and a VALUE. The KEY is $key and the VALUE is the quantity, so it is declared here: $this->session->data['cart'][$key] =

The cart session array is now filled. It could be small or it could be VERY LARGE depending upon how many products or options you have added to those products. Displayed below is a print_r() of a cart filled with 4 items. This is so you can see what exactly is in the array. You can do this at any time by running the following line:

<?php print_r($this->session->data['cart']);?>:

The above outputs:

Array ( [44] => 1 [47:YToxOntpOjIyNTtzOjEwOiIyMDExLTA0LTIyIjt9] => 1 [40] => 1 [30:YToxOntpOjIyNjtzOjI6IjE1Ijt9] => 1 )

Notice the KEY of each position is the product_id and serialized options array, separated by a ‘:’

This is just one example of how Opencart makes good use of arrays.

Looking for quality OpenCart Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , | Posted under OpenCart | RSS 2.0

Author Spotlight

Joe Stenhouse

Joe Stenhouse

I am a web application developer that specializes in PHP, JAVASCRIPT, MYSQL, HTML, and CSS. We manifest exciting potentials within the world wide web through means of innovation.

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + = 8

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>