-
Open Cart Coding Methods
Feb 19, 2018
Create a Custom Controller:
Today, we can implement a basic functionality demonstrating concepts of custom controllers. In the course of doing that, we can build the interface in front-end allowing certain guest users to submit their response by entering a name and message. Before proceeding, be assured that you have a working installation and Development in OpenCart. As it is pretty much the same, you can start applying through the Guestbook feature.
For those who are not familiar with an OpenCart arrangement, you can always look at the front-end controller comprising of the catalog/controller. The directory manages all controllers group wise, based on certain provided functionality.
In this particular case, creation and separation of the group called a guestbook is ideal. Go ahead and create your directory catalog/controller/guestbook. Within a directory, create the entry.php file with preceding content. Using controller file handling application logic as well as submission logic, use of Guestbook functionality carries out.
Open Cart Code Practice
<?php
class ControllerGuestbookEntry extends Controller {
private $error = array();
public function index() {
$this->load->language('guestbook/guestbook');
$this->document->setTitle($this->language->get('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->load->model('guestbook/guestbook');
$data['subject'] = sprintf('New guestbook entry submitted by %s', $this->request->post['guest_name']);
$data['message'] = $this->request->post['guest_message'];
$this->model_guestbook_guestbook->processGuestbookEntry($data);
$this->session->data['success'] = $this->language->get('text_success');
$this->response->redirect($this->url->link('guestbook/entry', '', true));
}
$data['success'] = '';
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('guestbook/entry', '', true)
);
$data['heading_title'] = $this->language->get('heading_title');
$data['entry_guest_name'] = $this->language->get('entry_guest_name');
$data['entry_guest_message'] = $this->language->get('entry_guest_message');
$data['entry_submit'] = $this->language->get('entry_submit');
if (isset($this->error['guest_name'])) {
$data['error_guest_name'] = $this->error['guest_name'];
} else {
$data['error_guest_name'] = '';
}
if (isset($this->error['guest_message'])) {
$data['error_guest_message'] = $this->error['guest_message'];
} else {
$data['error_guest_message'] = '';
}
$data['action'] = $this->url->link('guestbook/entry', '', true);
if (isset($this->request->post['guest_name'])) {
$data['guest_name'] = $this->request->post['guest_name'];
} else {
$data['guest_name'] = '';
}
if (isset($this->request->post['guest_message'])) {
$data['guest_message'] = $this->request->post['guest_message'];
} else {
$data['guest_message'] = '';
}
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$this->response->setOutput($this->load->view('guestbook/entry', $data));
}
protected function validate() {
if (utf8_strlen(trim($this->request->post['guest_name'])) < 1) {
$this->error['guest_name'] = $this->language->get('error_guest_name');
}
if (utf8_strlen(trim($this->request->post['guest_message'])) < 1) {
$this->error['guest_message'] = $this->language->get('error_guest_message');
}
return !$this->error;
}
}
Code for Open Cart
Each controller class provides indexed method handling where most logic of the controller is used. Next, you can search through certain codes in your indexing method, and create specific files. Most of the time, we can begin by inculcating your language file for a specific group. It is the way OpenCart manages static language labels through your application. Of course, it makes usage of multiple language-operated sites beneficial and one you can manage.
$this->load->language('guestbook/guestbook');
Before proceeding, let creation of the corresponding language file be so that the controller recovers it. Create a catalog/language/en-gb/guestbook/guestbook.php file with following contents.
<?php
// Heading
$_['heading_title'] = 'Guestbook';
// Entry
$_['entry_guest_name'] = 'Your Name';
$_['entry_guest_message'] = 'Message';
$_['entry_submit'] = 'Submit';
$_['text_success'] = 'Success: Your entry has been successfully submitted.';
// Error
$_['error_guest_name'] = 'Please enter Your Name!';
$_['error_guest_message'] = 'Please enter Message!';
As you realize, we just need assign labels with certain values in a language array. Coming to a controller, the following aspect is to set up an HTML title tag for your page.
$this->document->setTitle($this->language->get('heading_title'));
User conception has notification to use with a heading_title language variable defined in the language file created previously. In order to understand the following piece of code, you can create a stereotypical file. Therefore, for the moment, you can come down to the model file at catalog/model/guestbook/guestbook.php with these contents.
<?php
class ModelGuestbookGuestbook extends Model {
public function processGuestbookEntry($data) {
// send email notification to store admin
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$mail->setSubject($data['subject']);
$mail->setText($data['message']);
$mail->send();
}
}
-
PHP Code Snippet Use
Feb 12, 2018
Convert Seconds to Days, Hours and Minutes
Making a number of seconds to convert into minutes, hours and days to estimate the same amount of time on a different scale. This conversion process is achieved with use of the below code snippet written in PHP after making necessary calculations. Make use of this code snippet and enter the number of seconds you want to get conversion of in different units. The result automatically shows at the bottom of your screen.
function secsToStr($secs) {
if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
$r.=$secs.' second';if($secs<>1){$r.='s';}
return $r;
}
function secsToStr($secs) {
if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
$r.=$secs.' second';if($secs<>1){$r.='s';}
return $r;
}
<?php
$seconds = "56789";
$output = secsToStr($seconds);
echo $output;
?>
<?php
$seconds = "56789";
$output = secsToStr($seconds);
echo $output;
?>
PHP Code Snippet for Database Connection
If you are making a database in PHP and you want a MySQL database connection, you can always make use of the below shown snippet and use it when you want to connect it to your programmed database.
To store data, you would need a database. In this case, we would be using MySQL database.
<?php
$DBNAME = 'koonk';
$HOST = 'localhost';
$DBUSER = 'root';
$DBPASS = 'koonk';
$CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);
if(!$CONNECT)
{
echo 'MySQL Error: '.mysql_error();
}
$SELECT = mysql_select_db($DBNAME);
if(!$SELECT)
{
echo 'MySQL Error: '.mysql_error();
}
?>
<?php
$DBNAME = 'koonk';
$HOST = 'localhost';
$DBUSER = 'root';
$DBPASS = 'koonk';
$CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);
if(!$CONNECT)
{
echo 'MySQL Error: '.mysql_error();
}
$SELECT = mysql_select_db($DBNAME);
if(!$SELECT)
{
echo 'MySQL Error: '.mysql_error();
}
?>
In the highlighted lines above, you would have to specify your own server database details.
You can save the above file as config.php and you would have to include that file in all pages where you need database connectivity.
PHP Coding Practices
PHP Snippet for Directory Listing
Using the below PHP development code snippet you would be able to list all files and folders in a directory.
Trying to get all listing of files and folders in a directory, you need to use the code below until you get desired results.
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}
<?php
list_files("images/"); //This will list all files of images folder
?>
<?php
list_files("images/"); //This will list all files of images folder
?>
Detect User Language
Using the below PHP snippet you would be able to detect the language used in your browser. The language other than English uncommonly used when surfing the web, discovered through this PHP based code will make a difference to you when understanding the language on websites. You will just require considering the snippet below and find out the foreign language that your browser is using.
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}
Reading a CSV File
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
<?php
$csvFile = "test.csv";
$csv = readCSV($csvFile);
$a = csv[0][0]; // This will get value of Column 1 & Row 1
?>
<?php
$csvFile = "test.csv";
$csv = readCSV($csvFile);
$a = csv[0][0]; // This will get value of Column 1 & Row 1
?>
PHP Code Based on Open Source Platform
Creating a CSV File from PHP Array
Try using the code below and make a CSV file from the array provided. You can use it for easier access as well as store your data you need to use again in future.
function generateCsv($data, $delimiter = ',', $enclosure = '"') {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
return $contents;
}
function generateCsv($data, $delimiter = ',', $enclosure = '"') {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
return $contents;
}
<?php
$data[0] = "apple";
$data[1] = "oranges";
generateCsv($data, $delimiter = ',', $enclosure = '"');
?>
<?php
$data[0] = "apple";
$data[1] = "oranges";
generateCsv($data, $delimiter = ',', $enclosure = '"');
?>
Parsing XML Data
Below PHP snippet will help you explain how you can parse XML data in PHP.
This code snippet allows you to interpret XML coding for use in other projects where you find its application. It is commonly accepted as a tool you access as well as simplify and implement in the developmental process.
$xml_string="<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
//attribute are accessted by
echo $record['name'], ' ';
//node are accessted by -> operator
echo $record->symbol, ' ';
echo $record->code, '<br />';
}
$xml_string="<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
//attribute are accessted by
echo $record['name'], ' ';
//node are accessted by -> operator
echo $record->symbol, ' ';
echo $record->code, '<br />';
}
-
Initiating a business is a long and arduous process when you come down to maintaining it. Most benefits are availed through use of SEO that serves effectively when promoting on the web. These methods make small businesses go a long way getting you to find right consumers who try to relate to you and your ways of earning.
People who locate websites relating to businesses make it easier to promote and run businesses to earn enough revenue to fulfil business requirements. Digital Marketing and promotion is the right concern that changes with the use of SEO to improve your buying experience. Low-cost marketing is just a necessity and use of a positive approach to market your product online is consistent in most case.
To know a right approach to SEO is progressive development. To show you really care about your website-based product market is mainstream when it comes down to solving your business-related problems. To get people to businesses is a branch of SEO employing to move your site to a more productive and profiteering business.
Search engines serve as new age yellow pages providing you with the detail of products you purchase and tells you if you have enough resources. After surveying, results showed that more than 80% of all product purchases made with the use of major search engines where effective and recurrently seen in most operating businesses.
Best Affiliate Marketing Promotional Methods
Most people use search engines as well as yellow pages to find out information related to product sale and purchases online. To show acquirements as a source gets buyers the right resources selected by businesses to bloom at full potential. Try submitting the site you want to promote on search engines to see profiteering business growth.
Google and Bing have priority in searching the web and promote businesses to full potential where used. See that use of webmaster makes certain site Metadata always correctly in place and authenticated. Keywords and business names are compulsory and inclusive in the title with inclusion on the web to have the best use of your site.
Try not using keywords and titles in your content for the website you post and make an unambiguous descriptive illustration. Trying to check analytics on your website has easy decisions you want to know with Google Analytics, which is a Google, based tool and solves the problem of all characteristics related to your website.
SEO Techniques That Will Double Your Search Traffic
Signing up first and implementing code is just first few stages of website maintenance, as you need to start collecting data to see functionality and authenticity of your website. This tool tells amount of people visiting your site as well as time taken to browse as an experience when first clicking on the home page of your site.
-
Discovery of latest technology has moved marketplaces into a newer location, which relates more to machines rather than human effort. The evolution of Digital Marketing to advertise or publicize certain products is more common rather than the older method when selling in the market. People who want to purchase products through online methods search and find out through web-based retailers for trading.
Products sold faster and better are usually on the web and placed with discounts or promotions making it easier to sell. Surveys prove that most of the people who access and purchase through stores research through the web especially search engines such as Google and Bing. Most surveys showed a turnout of more than 75% numbering people who search online and purchase their stuff from web shops.
How to reach the consumer is simple and an evaluation of the number of clicks on the search engine links provides you with an estimate of the number of online customers. More online companies are considering a Digital Marketing survey method to make measures of this value and success there is behind it.
Digital Marketing considered, as the correct form of marketing is a process that provides accessibility to others of products on sale through websites. In addition, reaching and engaging with customers is a follow up you will see after using Digital Marketing methods with retail-based sales commonly made, which provides an ideal environment to sell your products.
Methods of Digital Marketing
You will never require making connections with certain organizers to understand the marketing and promotion processes. See that you meet proper Marketing professionals who work online and responsively getting your site to move to a better position on Google search engine for you to start trading through the web.
A means to understand a promotion based on Digital Marketing methods makes a high volume of sale of products. Use of content to acquaint with the site is advisable and a controlling reason to access through it is a purpose in retailing. A brand mentioned with the content makes most of the marketing come in process importantly when you want to post on your site.
Start to track customers the time they visit your site by availing information through cookies as well as other identification means. You can also notice the customer’s preferences, likes and dislikes that will guide you to what your product inclination is with placement on the web. It is where you get an insight into the customer behaviour and is a responsive way of web-based selling.
Digital Marketing Benefits to Drive Your Business Growth
With the track of your customer’s journey online gets you to make proper optimization in the design of your website when you are preparing to trade. Try making yourself present on the web and dominate through mobile phone access after contacting your clients repeatedly through this channel to start trading processes on your store.
-
Magento Best Practices
Jan 24, 2018
Website Development through magento web development agency is important to have assertive and thematically elevated design. Magento extension and perceptive means to make determination provided as a salient backup to develop site earnings as predicted. If use of extensions comes in the category of modular, flexible and extensible choice in development of websites.
Get instances of Magento’s complete code and use it to have perceptual programming practice with connections to code in development. Use of modules has one observer class ascertained and is properly executed through certainty in development and promotion. Observing through catalog_product_load_after, and use methods like catalogProductLoadAfter().
<?php
class Namespace_Module_Model_Observer {
public function catalogProductLoadAfter(Varien_Event_Observer $observer) {
// catalog_product_load_after
}
public function cmsBlockSaveBefore(Varien_Event_Observer $observer) {
// cms_block_save_before
}
}
Observer configurations are associated to different observer types:
The observer types involved include; object, model, singleton and disabled. With specification of a new model, the respective class is involved in:
The use of newer abstract models new class instantiations include add up with up.
<global>
<events>
<catalog_product_load_after>
<observers>
<namespace_modulename>
<type>singleton</type> <!-- use singleton instead of model -->
<class>namespace_modulename/observer</class>
<method>catalogProductLoadAfter</method>
</namespace_modulename>
</observers>
</catalog_product_load_after>
</events>
</global>
Practices for Programming Magento E-Commerce Stores
Model nodes have two different abstractions applied. One relates to concrete class and the other is a factory method to rewrite class methods and names. If you use a concrete class name, others will need to rewrite class names:
<?xml version="1.0"?>
<config>
<global>
<events>
<catalog_product_load_after>
<observers>
<namespace_modulename>
<type>singleton</type>
<!-- NOT Namespace_Module_Model_Observer! -->
<class>namespace_module/observer</class>
<method>catalogProductLoadAfter</method>
</namespace_modulename>
</observers>
</catalog_product_load_after>
</events>
</global>
</config>
Resolve Conflicts through Dependency
No two modules rewrite same classes. The last one is always a successor. Meaning of “in” is that the last one to have their configuration loaded is one you can rewrite as a class. All previous entries overwritten implement in coding. This has knowledge as rewrite conflict to access in different situation.
<?xml version="1.0" encoding="UTF-8" ?>
<config>
<modules>
<Namespace_Module1>
<active>true</active>
<codePool>local</codePool>
<depends>
<Namespace_Module2 />
</depends>
</Namespace_Module1>
</modules>
</config>
Specify the code for rewritten modular:
<?xml version="1.0"?>
<config>
<global>
<models>
<catalog>
<rewrite>
<product>Namespace_Module2_Model_Catalog_Product</product>
</rewrite>
</catalog>
</models>
</global>
</config>
Programming Best Practices
Declare Layout Updates
Plenty of times, your customizations are in models (“M” of MVC) and views (“V” of MVC) throughout Magento. This means you have to create template and layout files. If modules require any sort of manipulation of view layer, declare a layout update in the module’s configuration file.
<config>
<frontend>
<layout>
<updates>
<namespace_module>
<file>namspace/module.xml</file>
</namespace_module>
</updates>
</layout>
</frontend>
</config>
Uninstall Database Changes
This one is tough one. With truthfulness, hardly anyone does this. If you go to create a sort of database modification, such as creating an attribute, table, adding or creating system configurations, you need to provide a method to rid yourself of these in case someone decides never to implement a module.
Now before you go looking at the situation with odd thoughts and mention, “Magento does not provide a way to uninstall alterations” or the like, you will think to quit your whining. If you are experienced. You should not use the store at stake by needing modules enabled in order to operate. It is messy coding and you can make a better choice.
<?php
include_once 'abstract.php';
class Namespace_Module_Uninstall extends Mage_Shell_Abstract {
public function run() {
$this->removeDirectories();
$this->removeAttributes();
}
/**
* Remove file system files here.
*/
public function removeDirectories() {
$file = new Varien_Io_File();
$file->rmdir(BP . DS . 'app/code/local/My/', true);
$file->rm(BP . DS . 'app/etc/modules/My_Module.xml');
}
/**
* Remove any attributes here
*/
public function removeAttributes() {
$installer = $this->_getSetup();
$installer->startSetup();
// repeat this for any other attributes you wish to uninstall
$installer->removeAttribute('catalog_product', 'your_attribute');
$installer->endSetup();
}
/**
* Return catalog/customer/core or whichever resource setup class you need
*
* @return Mage_Catalog_Model_Resource_Setup
*/
protected function _getSetup() {
return Mage::getResourceSingleton('catalog/setup', 'default_setup');
}
}
$uninstall = new Namespace_Module_Uninstall();
$uninstall->run();