PHP functional HTML rendering

Working with HTML integration while writing code is sometimes tedious and time consuming, most of the times just copy paste.

Recently viewed a post about adding some fun in doing so.

Some may found it complicated, some may found unnecessary. but someone who are keen to explore new things or hidden things here is example.

 

First start with two basic functions that will carry out most of our complicated things

 

function tag(){
$args = func_get_args();
$nm = array_shift($args);
$content = array_shift($args);
$attrs = array_chunk($args, 2);
echo “<$nm “;
foreach($attrs as $chunk)
echo $chunk[0].’=’.'”‘.$chunk[1].'” ‘;
echo ‘>’;
if(is_string($content) || is_numeric($content) || empty($content))
echo $content;
else
$content();
echo “</$nm>”;
}

function etag(){
$args = func_get_args();
$nm = array_shift($args);
$attrs = array_chunk($args, 2);
echo “<$nm “;
foreach($attrs as $chunk)
echo $chunk[0].’=’.'”‘.$chunk[1].'” ‘;
echo “/>”;
}

So the first argument to our tag function is the tag name, second is the content to render inside the tag and the rest of the arguments are the attribute name and value pairs. Same goes for the etag function which renders empty elements, but then sans the content argument of course.

Below are a few examples of usage, first a simple login form.

tag(‘div’, function(){
tag(‘form’, function(){
echo ‘Username:’;
etag(‘input’, ‘type’, ‘text’, ‘name’, ‘username’);
echo ‘Password:’;
etag(‘input’, ‘type’, ‘password’, ‘name’, ‘password’);
etag(‘input’, ‘type’, ‘submit’, ‘value’, ‘Submit’, ‘name’, ‘submit’);
}, ‘method’, ‘post’);
}, ‘class’, ‘normal-pad’);

Then a more complicated scenario where we want to render a table of statistics:

function statsTable($stats, $headers, $fields, $sums){
tag(‘table’, function() use ($stats, $sums, $headers, $fields){
tag(‘tr’, function() use ($headers){
foreach($headers as $header)
tag(‘th’, $header);
});
foreach($stats as $s){
tag(‘tr’, function() use ($s, $fields){
foreach($fields as $field)
tag(‘td’, $s[$field]);
});
}
tag(‘tr’, function() use ($sums, $fields){
foreach($fields as $field)
tag(‘td’, is_numeric($sums[$field]) ? $sums[$field] : ”);
}, ‘class’, ‘sum-row’);
}, ‘class’, ‘stats-table’);
}

 

 

Nutch 2.3 + ElasticSearch 1.4 + HBase 0.94 Setup

Info

This guide sets up a non-clustered Nutch crawler, which stores its data via HBase. We will not learn how to setup Hadoop et al., but just the bare minimum to crawl and index websites on a single machine.

Terms

  • Nutch – the crawler (fetches and parses websites)
  • HBase – filesystem storage for Nutch (Hadoop component, basically)
  • Gora – filesystem abstraction, used by Nutch (HBase is one of the possible implementations)
  • ElasticSearch – index/search engine, searching on data created by Nutch (does not use HBase, but its down data structure and storage)

Requirements

Install OpenJDK, ant and ElasticSearch via your repository manager of choice (ES can be installed by using the .deb linked above, if you need).

Extract Nutch and HBase somewhere. From now on, we will refer to the Nutch root directory by$NUTCH_ROOT and the HBase root by $HBASE_ROOT.

Setting up HBase

  1. edit $HBASE_ROOT/conf/hbase-site.xml and add
    <configuration>
      <property>
        <name>hbase.rootdirname>
        <value>file:///full/path/to/where/the/data/should/be/storedvalue>
      property>
      <property>
        <name>hbase.cluster.distributedname>
        <value>falsevalue>
      property>
    configuration>
  2. edit $HBASE_ROOT/conf/hbase-env.sh and enable JAVA_HOME and set it to the proper path:
    -# export JAVA_HOME=/usr/java/jdk1.6.0/
    +export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/

    This step might seem redundant, but even with JAVA_HOME being set in my shell, HBase just didn’t recognize it.

  3. kick off HBase:
    $HBASE_ROOT/bin/start-hbase.sh

Setting up Nutch

  1. enable the HBase dependency in $NUTCH_ROOT/ivy/ivy.xml by uncommenting the line
    <dependency org="org.apache.gora" name="gora-hbase" rev="0.5" conf="*->default" />
  2. configure the HBase adapter by editing the $NUTCH_ROOT/conf/gora.properties:
    -#gora.datastore.default=org.apache.gora.mock.store.MockDataStore
    +gora.datastore.default=org.apache.gora.hbase.store.HBaseStore
  3. build Nutch
    $ cd $NUTCH_ROOT
    $ ant clean
    $ ant runtime

    This can take a while and creates $NUTCH_ROOT/runtime/local.

  4. configure Nutch by editing $NUTCH_ROOT/runtime/local/conf/nutch-site.xml:
    <configuration>
      <property>
        <name>http.agent.namename>
        <value>mycrawlernamevalue> 
      property>
      <property>
        <name>http.robots.agentsname>
        <value>mycrawlernamevalue> 
      property>
      <property>
        <name>storage.data.store.classname>
        <value>org.apache.gora.hbase.store.HBaseStorevalue>
      property>
      <property>
        <name>plugin.includesname>
        
        <value>protocol-httpclient|urlfilter-regex|parse-(text|tika|js)|index-(basic|anchor)|query-(basic|site|url)|response-(json|xml)|summary-basic|scoring-opic|urlnormalizer-(pass|regex|basic)|indexer-elasticvalue>
      property>
      <property>
        <name>db.ignore.external.linksname>
        <value>truevalue> 
      property>
      <property>
        <name>elastic.hostname>
        <value>localhostvalue> 
      property>
    configuration>
  5. configure HBase integration by editing $NUTCH_ROOT/runtime/local/conf/hbase-site.xml:
    <configuration>
      <property>
        <name>hbase.rootdirname>
        <value>file:///full/path/to/where/the/data/should/be/storedvalue> 
      property>
      <property>
        <name>hbase.cluster.distributedname>
        <value>falsevalue>
      property>
    configuration>

That’s it. Everything is now setup to crawl websites.

Adding new Domains to crawl with Nutch

  1. create an empty directory. Add a textfile containing a list of seed URLs.
    $ mkdir seed
    $ echo "https://www.website.com" >> seed/urls.txt
    $ echo "https://www.another.com" >> seed/urls.txt
    $ echo "https://www.example.com" >> seed/urls.txt
  2. inject them into Nutch by giving a file URL (!)
    $ $NUTCH_ROOT/runtime/local/bin/nutch inject file:///path/to/seed/

Actual Crawling Procedure

  1. Generate a new set of URLs to fetch. This is is based on both the injected URLs as well as outdated URLs in the Nutch crawl db.
    $ $NUTCH_ROOT/runtime/local/bin/nutch generate -topN 10

    The above command will create job batches for 10 URLs.

  2. Fetch the URLs. We are not clustering, so we can simply fetch all batches:
    $ $NUTCH_ROOT/runtime/local/bin/nutch fetch -all
  3. Now we parse all fetched pages:
    $ $NUTCH_ROOT/runtime/local/bin/nutch parse -all
  4. Last step: Update Nutch’s internal database:
    $ $NUTCH_ROOT/runtime/local/bin/nutch updatedb -all

On the first run, this will only crawl the injected URLs. The procedure above is supposed to be repeated regulargy to keep the index up to date.

Putting Documents into ElasticSearch

Easy peasy:

$ $NUTCH_ROOT/runtime/local/bin/nutch index -all

Query for Documents

The usual ElasticSearch way:

$ curl -X GET "http://localhost:9200/_search?query=my%20term"

How to install memcache on windows

Check your operating system whether 32bit or 64 bit. Based on that you need to download the binary version.

  1. 64bit Os – http://s3.amazonaws.com/downloads.northscale.com/memcached-win64-1.4.4-14.zip

  2. 32bit Os – http://code.jellycan.com/memcached/

  • Place the binary file on C or D location
  • Now Run the Command Prompt as Administrator – type the cmd –  C:/memcached/memcached.exe  -d install
  • Once Installed, Start the service – C:\memcached\memcached.exe -d start
  • Verify the service running properly on Start- > Run -> services.msc
  • Check your php extensions directory for php_memcache.dll
  • If you don’t have it, Download http://pecl.php.net/package/memcache/3.0.8/windows
  • Now Edit the Php.ini file and add following lines at extension section
  1. extension=php_memcache.dll
  2. Restart your apache server and Now we are good go.

If you are using Drupal then add below lines to settings.php

$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

you can check the memcahce settings at “admin/reports/memcache”

 

If you are using Core php then use below code for checking memcache working or not.

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
?>

Install SASS on Windows

  • The fastest way to get Ruby on your Windows computer is to use Ruby Installer.
  • After Ruby install Go to command prompt, C:\Ruby200-x64\bin folder use following command to install the SASS.
  • gem install sass
  • check version of SASS using following command
  • sass –v
  • install compass using following command
  • gem install compass
  • After install compass add ruby bin path i.e. C:\Ruby200-x64\bin in your local system environment variables path (My computer => properties => Advanced system settings => Advanced => Enviroment variables => path )
  • Restart the system.
  • Using Command prompt go to your project folder i.e. C:\xampp\htdocs\example
  • Compass watch
  • Change in css file and see the information in command prompt

Using Twig library with Codeigniter

Quite few days back worked on TWIG the template engine for PHP and tried if can be used in my existing codeigniter setup

Want to share following quick steps which may be useful for using with codeigniter

Step 1

Create Twig cache directory under “application / cache ” folder and make sure its writable..

Step 2

Download the TWIG library HERE and put in libraries folder so it will follow following directory structure

application/libraries/Twig
|-- Error
|-- Extension
|-- Filter
|-- Function
|-- Loader
|-- Node
|   `-- Expression
|       |-- Binary
|       `-- Unary
|-- NodeVisitor
|-- Sandbox
|-- Test
`-- TokenParser

Now create Library files

File 1=> application/libraries/Twig.php

################################################

<?php if (!defined(‘BASEPATH’)) {exit(‘No direct script access allowed’);}
class Twig
{
private $CI;
private $_twig;
private $_template_dir;
private $_cache_dir;
/**
* Constructor
*
*/
function __construct($debug = false)
{
$this->CI =& get_instance();
$this->CI->config->load(‘twig’);
ini_set(‘include_path’,
ini_get(‘include_path’) . PATH_SEPARATOR . APPPATH . ‘libraries/Twig’);
require_once (string) “Autoloader” . EXT;
log_message(‘debug’, “Twig Autoloader Loaded”);
Twig_Autoloader::register();
$this->_template_dir = $this->CI->config->item(‘template_dir’);
$this->_cache_dir = $this->CI->config->item(‘cache_dir’);
$loader = new Twig_Loader_Filesystem($this->_template_dir);
$this->_twig = new Twig_Environment($loader, array(
                ‘cache’ => $this->_cache_dir,
                ‘debug’ => $debug,
));
foreach(get_defined_functions() as $functions) {
             foreach($functions as $function) {
                 $this->_twig->addFunction($function, new Twig_Function_Function($function));
             }
         }
}
public function add_function($name)
{
$this->_twig->addFunction($name, new Twig_Function_Function($name));
}
public function render($template, $data = array())
{
$template = $this->_twig->loadTemplate($template);
return $template->render($data);
}
public function display($template, $data = array())
{
$template = $this->_twig->loadTemplate($template);
/* elapsed_time and memory_usage */
$data[‘elapsed_time’] = $this->CI->benchmark->elapsed_time(‘total_execution_time_start’, ‘total_execution_time_end’);
$memory = (!function_exists(‘memory_get_usage’)) ? ‘0’ : round(memory_get_usage()/1024/1024, 2) . ‘MB’;
$data[‘memory_usage’] = $memory;
$template->display($data);
}
}
###########################################

File 2 application/config/twig.php

##############################################
<?php if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
$config[‘template_dir’] = APPPATH.’views’;
$config[‘cache_dir’] = APPPATH.’cache/twig’;
###################################3

Step 3 USAGE

Put in you controller
$this->load->library('twig');

$data['title'] = "twig loaded";

$this->twig->display('view.html', $data);


simple huh…..

 

reference 

Common coding pitfalls for beginners as well as for experts

Even though we are having more  experience then too at some expert level we too do some beginner level mistakes, for me this is 100% true

 

Found one post on google reader from NetTuts+ want to share it for viewers. Please note that its not mine but sharing as liked it.

 

Learn from our mistakes; don’t do these things!

 


JavaScript Tips

1 – Unnecessary DOM Manipulation

The DOM is slow. Limiting your interaction with it will greatly increase your code’s performance. Consider the following (bad) code:

// anti-pattern
for (var i = 0; i < 100; i++){
	var li = $("<li>").html("This is list item #" + (i+1));
	$("#someUL").append(li);
}

This code actually modifies the DOM 100 times, and unnecessarily creates 100 jQuery objects. 100! A more correct approach would be to either use a document fragment, or build up a string that contains the 100 <li/> elements, and then appends that HTML to the containing element. That way, you jump into the DOM a total of once. Here’s an example:

var liststring = "";
for (var i = 100; i > 0; i--){
	liststring += "<li>This is list item #" + (99- i);
}
document.getElementById("someUL").innerHTML(liststring);

As noted above, with this technique, we touch the DOM only once, which is an improvement, but it also relies on string concatenation to build a large string. There’s a different way that we could approach this, using arrays.

var liststring = "<li>"
var lis = [];
for (var i = 100; i > 0; i--){
	lis.push("This is list item #" + (99- i));
}
liststring += lis.join("</li><li>") + "</li>";
document.getElementById("someUL").innerHTML(liststring);

When building large strings, storing each piece of the string as an item within an array element and calling join() is more efficient than string concatenation. This is one of the fastest and easiest ways to build repetitive HTML in JavaScript without using a template library or framework.

2 – Inconsistent Variable & Function Names in JavaScript

This next item isn’t a performance issue, but is extremely important – especially if you are working on code that other people work on, as well. Keep your identifiers (variable and function names) consistent. Consider the following variables as an example:

var foo = "bar";
var plant = "green";
var car = "red";

It wouldn’t make sense to add another variable, called Something. This introduces inconsistency in your variable naming pattern, causing your brain to cognitively flag this variable as being different or special. This is why constants in most languages are traditionally defined with all caps.

You can take this a step further by maintaining similar length, grammatical structure, and explanatory nature when naming functions. For example, consider the following contrived function:

function subtractFive(number){
	return number - 5;
}

Naming a function that adds five to a given number should follow the same pattern, shown here:

function addFive(number){
	return number + 5;
}

Sometimes, you might name a function to indicate its return value. For instance, you might name a function that returns an HTML stringgetTweetHTML(). You might also prepend a function’s name with do, if the function simply performs an operation and doesn’t return a value, eg:doFetchTweets().

Constructor functions typically follow the tradition of classes in other languages, capitalizing the first letter:

function Dog(color){
	this.color = color;
}

As a general rule of thumb, you should be descriptive when naming your identifiers. Classify them together with other similar identifiers by maintaining a naming pattern that is readable and offers hints to the nature of a variable or function’s purpose.

3 – Use hasOwnProperty() in for...in Loops

JavaScript’s arrays are not associative; trying to use them as such is frowned upon by the community. Objects, on the other hand, can be treated as hash tables, and you can iterate over an object’s properties by using the for...inloop, like so:

for (var prop in someObject) {
    alert(someObject[prop]); // alert's value of property
}

The problem, however, is that the for...in loop iterates over every enumerable property on the object’s prototype chain. This can be problematic if you only want to use the properties that exist on the actual object.

You can solve this issue by using the hasOwnProperty() method. Here’s an example:

for (var prop in someObject) {
    if (someObject.hasOwnProperty(prop)) {
        alert(someObject[prop]); // alert's value of property
    }
}

This version only alerts the values of the properties that directly reside onsomeObject.

4 – Comparing Boolean Values

Comparing boolean values in a condition is a waste of computation time. Take a look at the following for an example:

if (foo == true) {
    // do something for true
} else {
    // do something for false
}

Notice the condition: foo == true. The comparison of foo and true is unnecessary because foo is already a boolean value (or it’s a truthy or falsey one). Instead of comparing foo, simply use it as the condition, like this:

if (foo) {
    // do something for true
} else {
    // do something for false
}

To test for false, use the logical NOT operator, as shown below:

if (!foo) {
    // do something if foo is false
} else {
    // do something if foo is true
}

5 – Event Binding

Events are a complicated subject in JavaScript. Gone are the days of inlineonclick event handlers (except in some very rare “splash page” cases). Instead, use event bubbling and delegation.

Let’s imagine that you have a grid of pictures that need to launch a modal lightbox window. Here’s what you shouldn’t do. Note: we’re using jQuery here, assuming you are using a similar library. If not, the same bubbling principles also apply to vanilla JavaScript.

The relevant HTML:

<div id="grid-container">
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	<a href="someimage.jpg"><img src="someimage-thumb.jpg"></a>
	...
</div>

The (bad) JavaScript:

$('a').on('click', function() {
	callLightbox(this);
});

This code assumes that calling the lightbox involves passing an anchor element that references the full size image. Instead of binding to each anchor element, bind to the #grid-container element instead.

$("#grid-container").on("click", "a", function(event) {
	callLightbox(event.target);
});

In this code, both this and event.target refer to the anchor element. You can use this same technique with any parent element. Just make sure to define the element that should be the event’s target.

6 – Avoid Ternary Redundancy

The overuse of ternary statements is quite common both in JavaScript and PHP.

// javascript
return foo.toString() !== "" ? true : false;

// php
return (something()) ? true : false;

A condition expression always returns a true or false value, meaning you don’t need to explicitly add true/false as ternary values. Instead, you could simply return the condition:

// javascript
return foo.toString() !== "";

// php
return something();

PHP Tips

7 – Use Ternary When Appropriate

if...else statements are a central part of most languages. But doing something simple, such as assigning a value to a variable based upon a condition – well, they can junk up your code. Consider the following code:

if ($greeting)
{
    $post->message = 'Hello';
}
else
{
    $post->message = 'Goodbye';
}

This code can be reduced to one line, while still maintaining readability by using the ternary operator, like this:

$post->message = $greeting ? 'Hello' : 'Goodbye';

It’s clear, concise, and gives you the functionality you need.

As useful as the ternary operator is, the most important guideline is not to over-use it! The goal of coding is not to cramp your logic into as few lines as possible.

8 – Throw Exceptions Instead of Inception-Style Nesting

Let’s face it: many levels of nesting is ugly and difficult to maintain/read. The following code is a relatively simplified example, but they get much worse over time:

// anti-pattern
$error_message = null;
if ($this->form_validation->run())
{
	if ($this->upload->do_upload())
	{
		$image = $this->upload->get_info();
		if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
		{
			$error_message = 'There was an error creating the thumbnail.';
		}
	}
	else
	{
		$error_message = 'There was an error uploading the image.';
	}
}
else
{
	$error_message = $this->form_validation->error_string();
}
// Show error messages
if ($error_message !== null)
{
	$this->load->view('form', array(
		'error' => $error_message,
	));
}
// Save the page
else
{
	$some_data['image'] = $image['file_name'];
	$this->some_model->save($some_data);
}

That’s some nasty code, but you can make it drastically cleaner by using exceptions, like so:

try
{
	if ( ! $this->form_validation->run())
	{
		throw new Exception($this->form_validation->error_string());
	}
	if ( ! $this->upload->do_upload())
	{
		throw new Exception('There was an error uploading the image.');
	}
	$image = $this->upload->get_info();
	if ( ! $this->image->create_thumbnail($image['file_name'], 300, 150))
	{
		throw new Exception('There was an error creating the thumbnail.');
	}
}
// Show error messages
catch (Exception $e)
{
	$this->load->view('form', array(
		'error' => $e->getMessage(),
	));
	// Stop method execution with return, or use exit
	return;
}
// Got this far, must not have any trouble
$some_data['image'] = $image['file_name'];
$this->some_model->save($some_data);

It might be the same number of lines, but it allows for considerably more readable and maintainable code. It also avoids those difficult debugging sessions, where you’ve missed a possible path through the if statement. Keep it simple!

9 – False-Happy Methods

Being exception-happy is far more advantageous than being false-happy.

Ruby or Python developers are used to watching for trivial exceptions. While that sound tedious, it’s actually quite a good thing. If anything goes wrong, an exception is thrown, and you instantly know where the problem is.

In PHP – and especially when using older frameworks, such as CodeIgniter – you get what I refer to as “false-happy code” (as opposed to exception-happy). Instead of having an exception get all up in your face, it just returns a falsevalue and assigns the error string to some other property. This forces you to fish it out of the class using a get_error(); method.

Being exception-happy is far more advantageous than being false-happy. If an error occurs within your code (eg: could not connect to S3 to upload an image, or a value is empty, etc.), then throw an exception. You can also throw specific types of exceptions by extending the Exception class, like so:

class CustomException extends Exception {}

Throwing a custom exception makes debugging considerably easier.

Tip 10 – Use Guard Clauses

It’s common to use if statements to control a function or method’s execution path. It’s tempting to test a condition and execute a lot of code when the condition results in true, only to simply return in the else statement. For example:

function someFunction($param) {
    if ($param == 'OK') {
       $this->doSomething();
       return true;
    } else {
       return false;
    }
}

This kind of solution, however, represents a potential for spaghetti code. You can make this code easier to read by reversing the condition. Here’s the better version:

function someFunction($param) {
    if ($param != 'OK') return false;
    $this->doSomething();
    return true;
}

Isn’t that easier to read? It’s a simple change that makes a drastic difference in the readability of your code.

Tip 11 – Use while for Simple Iterations

The for loop is commonly used when you need, for example, a counter. Here’s a simple for loop:

for (var i = 0; i < x; i++) {
    ...
}

There are some very good reasons to use a for loop, but a while loop may be better if you just need something simple, like this:

var i = x;
while (i--) {
    ...
}

It doesn’t work in every situation, but it is an alternative.

Tip 12 – Keep Methods Maintainable

This is easily one of the most frequent mistakes made by newcomers.

A method is an object’s unit of work, and limiting your methods to a maintainable size makes your code easier to read and maintain. Take a look at the following monster method:

class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this->goAndDressUp();
			$this->washYourTeeth();
			$this->cleanYourWeapon();
			$this->takeYourHelmet();
			if($this->helmetDoesNotFit())
				$this->takeAHat();
			else
				$this->installHelmet();
			$this->chekcYourKnife();
			if($this->myAirplain() == "F22")
				$this->goToArmyAirport();
			else
				$this->goToCivilianAirport();
			$this->aim();
			$this->prepare();
			$this->fire();
		}
	}
}

Consider breaking this monster method into smaller, descriptive chunks, each being responsible for performing one well-abstracted action. This is easily one of the most frequent mistakes made by newcomers.

class SomeClass {
	function monsterMethod() {
		if($weArePilots) {
			$this->prepareYourself();
			$this->tryHelmet();
			$this->findYourAirport();
			$this->fightEnemy();
		}
	}
	private function prepareYourself() {
		$this->goAndDressUp();
		$this->washYourTeeth();
		$this->cleanYourWeapon();
		$this->chekcYourKnife();
	}
	private function tryHelmet() {
		$this->takeYourHelmet();
		if($this->helmetDoesNotFit())
			$this->takeAHat();
		else
			$this->installHelmet();
	}
	private function findYourAirport() {
		if($this->myAirplain() == "F22")
			$this->goToArmyAirport();
		else
			$this->goToCivilianAirport();
	}
	private function fightEnemy() {
		$this->aim();
		$this->prepare();
		$this->fire();
	}
}

There we go: cleaner, and easier to debug!

Step 13 – Avoid Deep Nesting

Too many levels of nesting makes code difficult to read and maintain. Consider the following:

function doSomething() {
    if ($someCondition) {
        if ($someOtherCondition) {
            if ($yetSomeOtherCondition) {
                doSomethingSpecial();
            }
            doSomethingElse();
        }
    }
}

You can refer to Tip #10 to make this code easier to read by reversing some of the conditions.

function doSomething() {
    if (!$someCondition) {
        return false;
    }
    if (!$someOtherCondition) {
        return false;
    }
    if ($yetSomeOtherCondition) {
        doSomethingSpecial();
    }
    doSomethingElse();
}

This code is considerably cleaner and produces the same results as before.

When you find yourself with nested if statements, closely examine your code; your method may be performing more than one task. Here’s an example:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		if($anotherThing)
			$this->doSomethingElse();
	}
}

In these cases, extract the nested methods into their own method:

function someFunc() {
	if($oneThing) {
		$this->doSomething();
		$this->doAnotherThing($anotherThing);
	}
}
private doAnotherThing($anotherThing) {
	if($anotherThing)
		$this->doSomethingElse();
}

Tip 14 – Avoid Magic Numbers and Strings

Magic numbers and strings are evil. Define variables or constants with the values you want to use in your code.

Instead of this:

function someFunct() {
	$this->order->set(23);
	$this->order->addProduct('superComputer');
	$this->shoppingList->add('superComputer');
}

Specify what those numbers and strings mean, and assign them to a variable with a meaningful name, like this:

function someFunct() {
	$orderId = 23;
	$selectedProductName = 'superComputer';
	$this->order->set($orderId);
	$this->order->addProduct($selectedProductName);
	$this->shoppingList->add($selectedProductName);
}

While some might argue that we’re needlessly creating variables, the performance hit is negligible. Readability always takes priority. Remember: don’t optimize for performance until you can describe why it’s necessary.

Step 15 – Use Built-In Array Functions

Use the built-in array functions instead of foreach().

Not Ideal:

foreach (&$myArray as $key =>$element) {
   if ($element > 5) unset ($myArray[$key]);
}

Better:

$myArray = array_filter($myArray, function ($element) { return $element <= 5;});

PHP offers a variety of array methods. They’re confusing at first, but take a day and try to learn as many as possible.

Tip 16 – Don’t Overuse Variables

It’s easy to overuse variables, but remember that variables are stored in memory. For every variable you create, the system needs to allocate memory for that variable. Look at this code:

public function get_posts() {
	$query = $this->db->get('posts');
	$result = $query->result();
	return $result;
}

The $result variable isn’t necessary. The following code omits that variable:

public function get_posts() {
	$query = $this->db->get('posts');
	return $query->result();
}

The difference is subtle, but we were able to improve this simple example. We kept the $query variable because it relates to the database, while $resultrelated more to our logic.


General Programming Recommendations

Tip 17 – Rely on the Database Engine

Anything less is a code smell.

A database is designed for working with data; use its tools and abilities to make your application more efficient.

For example, you can avoid redundant database queries in many circumstances. Most plug-and-play user management scripts use two queries for user registration: one to check whether the e-mail/username already exists and another to actually add it to the database. A much better approach is to set the username field to UNIQUE. You can then use native MySQL functions to check whether or not the record was added to the database.

Tip 18: Properly Name Your Variables

The days of naming your variables xyz are over (unless, of course, you’re dealing with a coordinate system). A variable represents an important part of your logic. Don’t want to type a long name? Get a better IDE. Modern IDEs auto-complete variable names in a blink of an eye.

Always be coding for six months from now. Are you certain that you’ll remember what that $sut variables refers to a year from now? Likely not: be descriptive. Anything less is a code smell.

Tip 19 – Methods Represent Actions

Mistakes happen; the key is to learn from them.

Name your methods with verbs representing the action they perform. The main concept is the exact opposite of the variable naming scheme. Use a short, but descriptive, name in a large scope (ie: public methods), and use a longer and more detailed name in a short scope (ie: private / protected methods). This helps make your code read like well written prose.

Also avoid any language other than English, when naming your methods. It’s annoying to read function names like 做些什麼() or делатьчтото() in your project. It may be impossible for other programmers to understand your intent. While it might seem arrogant, for better or worse, English is the adopted language of code. Try to use it, if we’re working on a large team.

Tip 20: Structure Recommendations

Finally, code structure is just as important to readability and maintainability as anything else we’ve talked about today. Here are two recommendations:

  • Indent with four or two space-width tabs. Anything more, such as eight spaces, is too much and will make your code difficult to read.
  • Set a reasonable line-width and respect it. Forty characters in a line? We’re not in the ’70s any more; set your limit to 120 characters, put a mark on the screen, and force yourself or your IDE to respect that limit. 120 characters gives you a nice width without making you scroll.

Conclusion

“I’ve never made a stupid programming mistake.” — No one, ever.

Mistakes happen; the key is to learn from them. We at Nettuts+ have made, and will continue to make, mistakes. Our hope is that you learn from our mistakes so that you can avoid them in the future. But, to be honest, the best way to learn best practices is to make the mistakes yourself!

Thanks for reading!