OpenCart has many predefined methods that can be called anywhere, such as in the controller folder or in the model, and in the view template files. You can find system level library files atsystem/library/. The following shows the different methods, how they can be written, and what their functions are:
• Affiliate: You can find most of the affiliate code under the affiliate section, and check the files at catalog/controller/affiliate/ and likewise at catalog/model/affiliate/. The following are the list of methods we can use for the affiliate library:
° $this->affiliate->login($email, $password);
This command ensures that the e-mail and password are passed to the method. If the username (e-mail) and password match among
the affiliates, it logs into the affiliate section. You can find this code at catalog/controller/affiliate/login.php on the validate function.
° $this->affiliate->logout();
The affiliate is logged out. It means the affiliate ID will be cleared and its session will be destroyed, as well as the affiliate's first name, last name, e-mail, telephone number, and fax number are given empty values.
° $this->affiliate->isLogged();
It checks whether the affiliate is logged in. If you want to show some message to the logged-in affiliate only, can you do so, as follows:
if($this->affiliate->isLogged()){ echo "Welcome to the Affiliate Section";
}else { echo "You are not at Affiliate Section";
}
° $this->affiliate->getId();
When we echo the preceding line, it will show the active affiliate's ID.
° $this->affiliate->getFirstName();
When we echo the preceding line, it will show the active affiliate's first name.
° $this->affiliate->getLastName();
When we echo the preceding line, it will show the active affiliate's last name.
° $this->affiliate->getEmail();
When we echo the preceding line, it will show the active affiliate's e-mail.
° $this->affiliate->getTelephone();
When we echo the preceding line, it will show the active affiliate's telephone number.
° $this->affiliate->getFax();
When we echo the preceding line, it will show the active affiliate's fax number.
° $this->affiliate->getCode();
When we echo the preceding line, it will show the active affiliate's tracking code, which is used to track referrals.
• Cache: It consists of the cache files and is located under system/cache.
° $this->cache->get($key);
You can retrieve the cache file as per the key value passed with this method.
In the following example, if the cache file of country is found in the system/cache folder, it directly takes the data from there , else performs database queries to retrieve the country:
$country_data = $this->cache->get('country'); if (!$country_data) {
$query = $this->db->query(
"SELECT * FROM " . DB_PREFIX ."country
ORDER BY name ASC");
$country_data = $query->rows;
$this->cache->set('country', $country_data);
} return $country_data;
° $this->cache->set($key, $value);
It helps in creating the cache files. Considering the preceding example about the country cache file, if the cache file is not found in the system/cache folder, then queries to the database are performed and the retrieved data is set with the key of the country.
° $this->cache->delete($key);
It deletes the file in the cache folder as per the key value provided.
For example: $this->cache->delete('country'); deletes the country cache file.
• Captcha: Captcha functions are not automatically instantiated; you have to access them as follows:
° Write the captcha function under controller as follows:
public function captcha() {
$this->load->library('captcha');
$captcha = new Captcha();
$this->session->data['captcha'] = $captcha->getCode();
$captcha->showImage();
}
° When the template file is called, the Captcha image is shown.
<img src="index.php?route=controller/captcha" alt="" />
"controller/captcha" in the preceding code line is the path where you make the captcha function. For example, if you write the function in the information/information.php file, it will beinformation/ information.
• Cart: System-instantiated cart objects are available for use. They are as follows:
° $this->cart->getProducts();
It gives the list of all products in the array of the cart.
° $this->cart->add($product_id, $qty = 1, $option = array());
It adds products to the cart; just pass the product ID, your desired quantity, and your desired options.
° $this->cart->update($key, $qty);
If you need to update a product in the cart, this method is used where $key is the product ID and $qty is the quantity you added.
° $this->cart->remove($key);
If you want to remove a product from the cart, this method is used where $key is the product ID that you wish to remove.
° $this->cart->clear();
If you wish to remove all the products at once, this method is used.
° $this->cart->getWeight();
It gives the sum of the weight of all products in the cart which requires shipping.
° $this->cart->getSubTotal();
It gives the subtotal of all products which are in the cart before being taxed.
° $this->cart->getTaxes();
It gives the array of total taxes applied to the cart.
° $this->cart->getTotal();
It gives the total of all products in the cart after being taxed.
$this->cart->countProducts();
It gives the total number of products in the cart.
° $this->cart->hasProduct();
It checks whether the cart has products or not.
° $this->cart->hasStock();
It checks for the stock of each product in the cart. If it has stock, it returns true; else false (means no stock).
° $this->cart->hasShipping();
It checks whether each product in the cart has shipping or not. If a product has shipping, true is returned; else false.
° $this->cart->hasDownload();
It checks whether each product in the cart is downloadable or not. If a product is downloadable, true is returned; else false.
• Config: The config values are loaded from the Settings table of the database.
° $this->config->set($key, $value);
It is used to override the $key value of the "Settings" table value of the database. It does not save the value to the database.
For example, if you want to show a different store name than the set value in the database, we add the following code in the controller folder:
$this->config->set('config_name','New Store Name');
Normally, when we echo $this->config->get('config_name'); we get the store name; however since the set value is changed now, we will get the store name as "New Store Name".
° $this->config->get($key);
It returns the set value as per the $key value passed. If there is no key value, it returns null. For example, when you echo $this->config>get('config_name');, you will get the store name.
• Currency: It consists of the methods that can be applied to currencies:
° $this->currency->set($currency);
It sets or overrides the currency code to be used in the session as well as sets the cookie for the currency.
° $this->currency->format($number, $currency='', $value='', $format=true)
It formats the number to the currency passed. For example, if you have the number 100 and currency USD, it will be formatted to $100.00. Here $number is the price value, $currency is the currency code, $value is the conversion rate between the currencies, and $format is to format the currencies. For example $this->currency->format(50, 'USD', 1, false); gives 50.00 as the output and
$this->currency->format(50, USD, 1, true); gives $50.00 as the output.
By navigating to Admin | System | Localization | Currencies, we can find the settings where we insert the currency, the currency sign, the position of the sign, the decimal points to show, and so on.
° $this->currency->convert($value, $from, $to);
If currency is set from Admin| System| Localization| Currencies, the value passed is converted from a certain chosen currency to another.
° $this->currency->getId($currency='');
If you need the ID of the currency, we have to use the getId() method. For example, by using $this->currency->getId('USD');, you will get the ID of the US dollar. USD is the code for the currency inserted.
If no currency code is defined, it returns zero.
° $this->currency->getSymbolLeft(($currency='');
Some currencies' symbols appear to the left of the value; for example, $100 in the case of 100 US dollars. We can get the symbol on the left
side of the value with the use of the method. Now, echo $this>currency->getSymbolLeft('USD');
$this->currency->getSymbolRight(($currency='');
Some currencies' symbols appear on the right side of the value, for example, the Swedish, 100krona. We can get the symbol on the right side of the value with this method. Now, echo $this->currency-
>getSymbolRight('SEK');
° $this->currency->getDecimalPlace($currency='');
Navigate to Admin | System | Localization | Currencies | Insert Button, where there is a Decimal Places field to insert the currency. The setting is activated as per the activated currency. If we insert 2 in the input field and then save it after the decimal, two values are displayed: $100.00. Now, echo $this->currency-
>getDecimalPlace('USD');
° $this->currency->getCode();
It returns you the ISO code that you inserted at Admin | System | Localization | Currencies | Insert Button.
° $this->currency->getValue($currency = '');
It gives the set value of the Value field while inserting the currency. It is taken as the exchange rate for the specified currency with respect to the default currency.
° $this->currency->has($currency);
It checks whether the passed currency exists in the OpenCart currency list. If it finds the currency, it returns true; else false.
• Customer: It consists of the customer data.
° $this->customer->login($email, $password, $override = false);
It logs a customer in. It checks for the customer's username and password when $override is passed false, else only for current logged in status and the e-mail. If it finds the correct entry, the OpenCart wish list entries are retrieved. In addition to this, customer ID, first name, last name, e-mail, telephone, fax, newsletter subscription status, customer group ID, and address ID can also be globally accessed by the customer. It also updates the customer IP address from where he/she logs in.
$this->customer->logout();
When it is called, it logs out the customer. First of all, it updates the OpenCart wish list field of the customer table in the database and destroys the customer's session ID. Then, it assigns a blank value to the customer object's data such as customer ID, first name, last name, e-mail, telephone, fax, newsletter, customer group ID, and address ID.
° $this->customer->isLogged();
It checks whether the customer is logged in or not. If he/she is logged in, it returns true else false. For instance, consider the following lines of code:
if($this->customer->isLogged()){
echo "You are at the logged customer section";
}else{
echo "You have not logged in yet"; }
° $this->customer->getId();
When you echo it, it gives you the customer ID of the logged-in customer.
° $this->customer->getFirstName();
When we echo this line, we will show the active customer's first name.
° $this->customer->getLastName();
When we echo the preceding line, it will show the active customer's last name.
° $this->customer->getEmail();
When we echo the preceding line, it will show the active customer's e-mail address.
° $this->customer->getTelephone();
When we echo the preceding line, it will show the active customer's telephone number.
° $this->customer->getFax();
When we echo the preceding line, it will show the active customer's fax number.
$this->customer->getFirstName();
When we echo the preceding line, it will show the active customer's first name.
° $this->customer->getNewsletter();
When we echo the preceding line, it will show either 0 or 1, if 1 is shown, it means the customer is subscribed to the newsletter. If zero is shown, it means the customer is not subscribed to the newsletter.
° $this->customer->getCustomerGroupId();
When we echo the preceding line, it will show the active customer's group ID.
° $this->customer->getBalance();
When we echo the preceding line, it will show the active customer's current balance. When you view the "Your Transaction" link after logging in to the customer section, you will find the total current balance; the same balance is shown by this code.
° $this->customer->getRewardPoints();
When we echo the preceding line, it will show the active customer's total remaining reward points earned.
• Database: The db class helps to query the database to perform insert, select, delete, and update, as well as providing methods to clean the data by escaping, getting the last inserted ID, and the total count of rows.
° $this->db->query($sql);
It executes the passedsql statement. For instance, consider the following lines of code:
$query = $this->db->query("SHOW COLUMNS FROM
`".DB_PREFIX."product` LIKE 'youtube'"); if(!$query->num_rows){
$this->db->query("ALTER TABLE `".DB_PREFIX."product`
ADD `youtube` TEXT NOT NULL");
}
These lines of code are written in the controller file or model files of OpenCart. The method searches for the YouTube column in the product table, and if it is not found, it alters the producttable by adding another column named YouTube.
$this->db->escape($value);
It escapes or cleans the data before entering it to the database to avoid the SQL injection. Developers perform this for security reasons.
° $this->db->countAffected($sql);
It returns the count of affected rows from the most recent query execution.
° $this->db->getLastId($sql);
It returns the ID of the last inserted row from the most recent query execution.
• Document: Document library methods can be called from controller, only before rendering the document.
° $this->document->setTitle($title);
This line of code sets the page's title.
° $this->document->getTitle();
This line of code gets the page's title.
° $this->document->setDescription($description);
This line of code gets the page's meta description.
° $this->document->getDescription();
This line of code gets the page's meta description.
° $this->document->setKeywords($keywords);
This line of code sets the page's keyword meta tag.
° $this->document->getKeywords();
This line of code gets the page's keyword meta tag.
For the home page of OpenCart, the title and description keywords are accessed from the settings inserted at System | Settings | Edit and under the Store tab. And for other pages, title and description is set as defined to override the default values as per the need in the controller file.
$this->document->addLink($href, $rel);
It adds the link at the head section as follows:
$this->document->addLink($this->url->link(
'product/product', 'product_id=42','canonical');
If we write the preceding line of code in the controller file, we will see the following code at the head sections:
<link href="http://example.com/index.php?route= product/product&product_id=42"rel="canonical" />
A canonical page is the preferred version of a set of pages with highly similar content.
Why specify a canonical page? It's common for a site to have several pages listing the same set of products. For example, one page might display the products sorted in alphabetical order, while other pages display the same products listed by price or by rating.
Details of a canonical page can be found at the following URL: http://support.google.com/webmasters/bin/answer. py?hl=en&answer=139394
° $this->document->getLinks();
It lists the set links. Mostly, calls are made in the header of controller.
° $this->document->addStyle($href, $rel = 'stylesheet', $media = 'screen');
It adds the extra style sheet needed only in the page. For example, consider the following lines of code:
$this->document->addStyle('catalog/view/javascript/ jquery/colorbox/colorbox.css');
The colorbox.css file is needed in the product details page, so it is called in catalog/controller/product/product.php and the style sheet is added to the <head> section of the document.
$this->document->getStyles();
It lists the style sheet at the <head> section of the document. Mostly, calls are made in the header controller.
As with the addStyle method, colorbox.css is added, so a line is added in the <head> section of the document. The following is the line we can see on the <head> section of the document.
<link rel="stylesheet"type="text/css"href=
"catalog/view/javascript/jquery/colorbox/colorbox.css
"media="screen" />
° $this->document->addScript($script);
It adds the script files (for example, JavaScript files) needed only in the page. For example:
$this->document->addScript('catalog/view/javascript/ jquery/tabs.js');
This adds the tabs.js files wherever the preceding line of code is added.
° $this->document->getScripts();
It lists the script files added with the addScript method. Just as the addScript code in the preceding example, where the tabs.js file is added, the following line of code is added in the <head>section of the document:
<script type="text/javascript"src="catalog/view/ javascript/jquery/tabs.js"></script>
• Encryption: You can find the encryption file at system/library/ encryption.php which has the Encryption class and its object name is encryption. It is used to encrypt and decrypt the values. °$this->encryption->encrypt($value);
It encrypts the data based on the key in the admin settings. ° $this->encryption->decrypt($value);
It decrypts the data based on the key in the admin settings.
• Language: You can find all the data under catalog/language: ° $this->language->get($key);
It gets the value of the key from the language file. For example: $this->language->get('heading_title');
It searches for the value of heading_title in the language file.
° $this->language->load($filename);
It loads the language file and makes its variable for use. $this->language->load('catalog/category');
It loads the catalog/language/english/catalog/category. php file when the English language is active or loads the respective language's category.php.
• Length: You can find the length file at system/library/length.php which has the Length class and its object name is length. It is used to convert, format, and get the unit of length.
° $this->length->convert($value, $from, $to);
The passed value is converted as per the value provided. For example, consider the following lines of code:
$length = $this->length->convert($this->config->get(
'ups_length'), $this->config->get(
'config_length_class_id'), $this->config->get(
'ups_length_class_id'));
The configured length is converted to the UPS length.
° $this->length->format($value, $length_class_id, $decimal_point = '.', $thousand_point = ',');
The passed value is formatted to the required length format.
° $this->length->getUnit($length_class_id);
It returns the length's unit, such as cm or inches.
• Log: You can find all the log files stored under system/logs.
° $this->log->write($message);
It writes the message passed on to the system/logs/error.txt file. For example:
$this->log->write('This is the error message');
If you write this code and then refresh the URL which calls this file, the This is the error message message is logged in the error.txt file.
• Mail: You are shown an example directly for mail, which will help you understand the concept more clearly. With the following lines of code, an e-mail is sent:
$mail = new Mail();
$mail->setTo($this->request->post['email']);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender($this->config->get('config_name'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES,
'UTF-8'));
$mail->setText(html_entity_decode($message, ENT_QUOTES,
'UTF-8'));
$mail->send();
The setTo() method sets the receiver to whom the mail is addressed, the setFrom()method sets the sender's e-mail ID , setSender() sets the name of the sender, setSubject() sets the subject section of the mail, setText() sets the text for the message if it's only text (if it is an HTML e-mail, we use setHtml()), and the send()method sends the mail.
• Pagination: The following code snippet is a part of the user listing.
$pagination = new Pagination();
$pagination->total = $user_total;
$pagination->page = $page;
$pagination->limit = $this->config->get(
'config_admin_limit');
$pagination->text = $this->language->get(
'text_pagination');
$pagination->url = $this->url->link('user/user', 'token=
' . $this->session->data['token'] . $url .'&page={page}',
'SSL');
$this->data['pagination'] = $pagination->render();
total is the total number of users, page is the page number that is available through the GET value, limit is defined by the setting in the admin, text shows the numbers and extra messages, and urlis to move to other pages. With this rendering $pagination is available for the template view to show the page numbers.
• Request: Two commonly used methods for a request-response communication between a client and server are GET and POST. In OpenCart, these are written as follows:
° $this->request->get; ° $this->request->post;
For a selected element, it is respectively written as:
° $this->request->get['selected']; ° $this->request->post['selected'];
• Response: You can find the response system files at system/library/ response.php, which have a class name of Response and its object name is response.
$response = new Response();
° $response->addHeader('Content-Type: text/html; charset=utf-8');
The addheader()method adds the content type used by the document.
° $this->redirect($url);
It redirects the page to the URL specified. $url passed should have the complete URL.
• Session: It stores the active session data:
° $this->session->getId()
It returns the active session ID.
• Tax: System-initiated tax objects are used in OpenCart. They are as follows: ° $this->tax->setShippingAddress($country_id, $zone_id);
It sets the shipping address with the country ID and zone ID.
° $this->tax->setPaymentAddress($country_id, $zone_id); It sets the payment address with the country ID and zone ID.
° $this->tax->setStoreAddress($country_id, $zone_id);
It sets the store address with the country ID and zone ID.
° $this->tax->calculate($value, $tax_class_id, $calculate = true);
It calculates the tax, only if $tax_class_id is set and $calculate is set to true.
• URL: It helps in making the full URL. You can find the URL file at system/ library/url.php which has the class name url and its object name is url.
° $this->url->link($route, $args = '', $connection = 'NONSSL')
It makes the URL to be passed as the $route variable. If SSL is active, it makes https://; else http://.
• User: You can find most of the user code under the account section, and you can check the files at catalog/controller/account/. The following are the list of methods we can use for the user library:
° $this->user->getId();
When we echo the preceding line, it will show the active user's ID.
° $this->user->login($username, $password);
When the username and password are passed to the method, and if they match among the users, it logs in to the administration section.
° $this->users->logout();
The admin user gets logged out. It means that the user ID will be cleared, its session will be destroyed, and the user's username and user ID are assigned empty values.
° $this->users->isLogged();
It checks if the user is logged in or not.
° $this->users->hasPermission($key, $value);
It checks whether the user has permission or not. For example:
if (!$this->user->hasPermission('modify',
'catalog/category)) {
$this->error['warning'] = $this->language->get(
'error_permission');
}
The preceding code checks whether the user is provided access to modify or insert the categories. Permission for users can be provided by navigating to Admin | System | Users | User Group, where one can edit or insert a new user and provide the necessary permission to the user.
° $this->users->getId();
It returns the active user's ID.
° $this->users->getUserName();
It returns the active user's username.
• Weight: You can find the weight file at system/library/weight.php which has a class name Weight and its object name is weight and is used to convert, format, and get the unit of weight.
° $this->weight->convert($value, $from, $to);
The passed value is converted as per the value provided to the desired weight. The $value attribute is the weight of the products on the shopping cart, $from is the weight class needed to be converted, and $to is the required weight class. You can insert and edit the weight class by navigating to Admin | System | Weight Class.
° $this->weight->format($value, $weight_class_id, $decimal_point = '.', $thousand_point = ',');
The passed value is formatted to the required weight format.
° $this->length->getUnit($weight_class_id);
It returns the weight's unit, such as kg, pound, or gram.
Detailed description of the Featured module
The Featured module highlights specific products so that they will be helpful in increasing the sales and lets users know which products are highlighted.
No comments:
Post a Comment