googleads
Learn PHP Best Practices & Coding Standards In CodeIgniter
preloder
PHP Framework Web Development

Implementing The Best PHP Coding Standard And Practices In CodeIgniter

In our previous blogs, we have discussed more about PHP frameworks and its advancements, tutorials and lot more and this time we’re planning to write up a blog about the best PHP coding standard and practices to be followed in CodeIgniter. We all knew that CodeIgniter is the powerful PHP Open Source application development framework which help us to develop the application with the increased performance & speed with its rich functionalities, libraries and helpers. But CodeIgniter can do a lot more if  we try to follow some of the best tactics while developing an application so follow these standard methods to develop a secure & standard website to prevent it from various unusual issues. 

1) Tips To Make Readability & Proper Documentation

Regardless of the framework, always make sure to maintain the good naming Standards in all variable, file name, Class name, Controller Names. Coming to Variables, Variables should contain only lowercase letters and while setting up the variable name, make sure to have the meaningful and readable name followed by the underscore separators. Also make it reasonable to indicate their purpose of having it in code. Remember, a very short, non-word variables should only be used as iterators in for() loops.

For Example, listing down some of the best standards to follow,

$j = ‘foo’;            // Avoid single letter variables for c
$Str                    // should not contains uppercase starting letters
$bufferedText  // uses Camel Casing & could be shortened without losing semantic meaning
$group_id        // multiple words, needs to be separated using underscore
$name_of_last_city_used  // Avoid too long names

Add better comments to make the code readable and give the proper Indent for Code

Avoid unnecessary variables :

 

Ordinary way of declaring

 

Best To Follow,

 

Class names should be the filename of the ‘class’ and that should intimate the purpose of using it as Class. Also remember that the Constants should be declared in UPPER CASE.

Follow proper indentations on entire project development. Document the purpose of each file by adding the clear comments for each block.  Likewise, the other internal methods and variables such as utility and helper functions which are used for abstraction should be prefixed with an underscore.

For Example,

 

Related: Install & Configure The CodeIgniter On Ubuntu 16.04

 

2. Configuration Standards

The root or base URL of the site must be configured in the path of  “application/config/config.php file” and you can see how i have fetched the $config array & key “base_url” in below code:

 

By following this method, CodeIgniter will try to fetch the exact protocol, domain and path of the installation. At any case, if the path is not defined then Codeigniter will try to guess the path & domain randomly so sometimes it might also leads to get inappropriate results. So be sure to mention the path using above method and am pretty sure that this tactic will surely help us in production environments.

3. DB Configuration for Environments

With multidimensional array support, we can setup the database for different environment like production / integration / development). Database can also be configured in this path “application/config/database.php” of codeigniter.

For example, let me show you the small sample for development environment.

There you could see that i had set the default values for few options except hostname, username, password, database and dbdriver.

  • hostname − Location of database e.g. localhost or IP address
  • username − Username of database.
  • password − Password of database.
  • database − Name of the database.
  • dbdriver − Type of database e.g. MySQL, PostgreSQL.

By changing the key of the array $db, we can set other configurations of database. Also We can switch over the environment by simply defining the environment name as follows,

 

Best To Read: Best Laravel Security Practices You Must Try It Out!

 

4. Compatibility & Standards

If you’re concerned about the compatibility and standards of the codeigniter then its recommended to use PHP 5.6 or newer version, but basically it will be compatible from PHP 5.3.7 onwards. Additionally, do not use PHP functions if it requires to install other third party libraries unless its mandatory. Ensure that each and every request comes of CodeIgniter reaches only via index.php. and also ensure to follow MVC Standard development pattern to make the application reliable. The below image will you the over all process of MVC pattern.

5. Autoload Configuration

Autoload configuration describes the process of which part of the system should be loaded by default. Also its always advisable to load the minimal resources to keep the framework as lightweight.

Following things we can load automatically :−

  • Libraries − List of libraries in an array. Eg. $autoload[‘libraries’] = array(‘database’, ’email’, ‘session’);
  • Drivers − Classes are located in system/libraries/ or in application/libraries/ directory, but these are also placed inside the project sub directory and extend via CI_Driver_Library class. Eg. $autoload[‘drivers’] = array(‘cache’);
  • Helper files − List of libraries in the array will be auto-loaded by CodeIgniter. Eg. $autoload[‘helper’] = array(‘url’, ‘file’);
  • Custom config files − Can be used only when any custom configuration is need to be defined. Eg. $autoload[‘config’] = array(‘config1’, ‘config2’);
  • Language files − List of languages (without ‘_lang’) in an array.
  • Models − List of models in an array. Eg. $autoload[‘model’] = array(‘first_model’, ‘second_model’);

 

6. Error Handling

CodeIgniter provides an easy error handling mechanism, because we can able to display the error messages on index.php based on the various environments like development, test, production. For example, you can display the errors on development environment and can hide it from testing and production environment as follows.

 

Similarly, CodeIgniter supports three types of functionality to handle the errors,

  • show_error() function displays errors in HTML format at the top of the screen.
  • show_404() function displays error if the accessed page does not exists.
  • log_message() function is used to write custom log messages.

Hope these blogs gives you a clear view on Codeigniter coding standards but we’re about to share some advanced tricks for codeigniter so stay tuned with us and if you want a blog on interesting topic then don’t forget to share your thoughts on the comment section. We love to hear from you and will surely come up with some of the best picks!

The following two tabs change content below.

Annamalai

Tech lead at Agira, Around 10+ years of experience in IT industry; He demonstrated numerous success in various projects by directing the team with great guidance to apply the intense logics to accomplish the goal on time. Reliable working experience in modern web technologies, especially in Node.js and always loves to reserve his time in reading magazines & travelling.

One thought on “Implementing The Best PHP Coding Standard And Practices In CodeIgniter”

Leave a Reply

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

[contact-form-7 id="120788" title="Web Page Form"]

Schedule Your Call