In our previous blogs, we have discussed more 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 helps 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 contain uppercase starting letters
$bufferedText // uses Camel Casing & could be shortened without losing the semantic meaning
$group_id // multiple words need 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 :
The ordinary way of declaring
<?php $myMessage = trim($_POST['message']); echo $myMessage;
Best To Follow,
<?php echo trim($_POST['message']);
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 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.
public function convert_text() private function _convert_text()
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:
$config['base_url'] = 'http://domainname.com';
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 lead to getting inappropriate results. So be sure to mention the path using the 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 set up the database for a different environment like production/integration/development). The database can also be configured in this path “application/config/database.php” of Codeigniter.
For example, let me show you a small sample for the development environment.
$db['development'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'database_name', 'dbdriver' => 'mysql', 'dbprefix' => '', 'pconnect' => TRUE, 'db_debug' => TRUE, 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array() );
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 the 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 the database. Also, We can switch over the environment by simply defining the environment name as follows.
$active_group = ‘development’; //This will set the development environment $active_group = ‘test’; //This will set the test environment
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 it’s 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 overall process of the 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 the development environment and can hide it from testing and production environment as follows.
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
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 an error if the accessed page does not exist.
- 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 the 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!