Codeigniter Best Practices
22/06/2019 . 4 minutes, 4 seconds to read . Posted by Admin#codeigniter #best-practices
1. Follow the CI default structure
CodeIgniter comes with the default MVC pattern structure. Follow this basic structure. When using the MVC structure use Controllers for logins, Models for database interaction and Views for HTML.
2. Use CI form
Codeigniter has buitin form validation library that is easy to implement. I would recommend using CI form validations. It provides you the facility to set the rules, run validations and display messages.
To set the rules you can use the following syntax:$this->form_validation->set_rules();?
Example:
$this->form_validation->set_rules('email', 'Email', 'required');
You can also set cascading rules like this:
$this->form_validation->set_rules('email', 'Email', 'required|max_length[12]|is_unique[users.email]');
3. Sanitize your inputs
Always sanitize your inputs before submitting the data to the database. The application should prevent SQL (Structured Query Language) injections and to store only valid data into the database. Be sure that you always clean the inputs.
Example:
$employees = $this->security->xss_clean($employees);
Set it global in the configurations ,you can run this filter automatically each time there is a post requested or cookie data fetched.
$config['global_xss_filtering'] = TRUE;
Note: Sanitize_filename() is also used to cross-check the file inputs from the user.
4. Protect your site from Cross-Site Request Forgery (CSRF)
Enable CSRF it will protect your site from CSRF attack. You will find it in config file.
$config['csrf_protection'] = TRUE;
5. Try to use CI-preferred styling and commenting
CodeIgniter provides an excellent set of styles and commenting to format your code well. That way other developers can understand the code you are writing.
6. Use caching techniques like Query Caching
The database class is used to cache your queries and reduce the load time. CodeIgniter loads this class automatically. You don’t have to do it manually if caching is enabled. See below code and edit your database.php under config directory.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
7. Remove index.php from the URLs.
Always remove the index.php URLs to SEO-friendly URLs. Change your .htaccess code to make it work?
For example:
To change config file:
$config['index_page'] = "index.php"
//to
$config['index_page'] = ""
To change in your .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
8. Create helpers for your most-often-used functions
For the most commonly used functions always create the helpers. Helpers are the set of instructions or functions. To use the helpers, you have to load them. They do not load by default. This is how to load a helper:
$this->load->helper('helper_name');
9. The Config directory should have all the configuration information.
Keep all configuration files under the config directory. If they are outside the directory you may not be able to find them as easily. In the long run, putting the files into the directory will help when you’re working on big projects.
Note: Always load what is required for your application. Don’t load anything that is not needed. For this, you can use the constructor of your controller, if you only want to load part of the functionality.
10. Avoid unnecessary variables :
Bad
$myMessage = trim($_POST['message']);
echo $myMessage;
Good
<?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 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.
Example:public function convert_text()
private function _convert_text()?
11. 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.
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 error if the accessed page does not exists.
- log_message() function is used to write custom log messages.