CodeIgniter - Basic Concepts

Controllers
The controller is a simple class file. As the name suggests, it controls the entire application by URI.
Creating a Controller
First go to the application/controllers folder . There you will find two files: index.html and Welcome.php . These files are shipped with CodeIgniter.
Save these files as they are. Create a new file in the same path named " Test.php ". Write the following code in this file −
<? php
class Test extends CI_Controller {
public function index () {
echo "Hello World!" ; } } ?>
The Test class extends a built-in class named CI_Controller . This class needs to be extended whenever you want to create your own Controller class.
Controller call
The above controller can be called by URI like this:
http://www.your-domain.com/index.php/test
Notice the word " test " in the above URI after index.php. This points to the name of the controller class. Since we gave the controller name " Test ", we write " test " after index.php. The class name must start with an uppercase letter, but we need to write a lowercase letter when we call this controller from a URI. The general syntax for calling a controller is as follows:
http://www.your-domain.com/index.php/controller/method-name
Creating and calling a constructor method
Let's modify the above class and create another method called "hello".
We can execute the above controller in the following three ways:
- http://www.your-domain.com/index.php/test
- http://www.your-domain.com/index.php/test/index
- http://www.your-domain.com/index.php/test/hello
After visiting the first URI in the browser, we get the output as shown in the image below. As you can see, we got the output of the index method even though we didn't pass the method name to the URI. We have only used the controller name in the URI. In such situations, CodeIgniter calls the default " index " method.
By visiting the second URI in the browser, we get the same output as shown in the picture above. Here we have passed the method name after the controller name in the URI. Since the method name is " index ", we get the same result.
By visiting the third URI in the browser, we get the output as shown in the figure below. As you can see, we get the output of the " hello " method because we passed " hello " as the method name after the controller name " test " in the URI.
Memory glasses
- The controller class name must start with a capital letter.
- The controller must be called in lower case.
- Don't use the same method name as your parent class as it will override the functionality of the parent class.
The controller class name must start with a capital letter.
The controller must be called in lower case.
Don't use the same method name as your parent class as it will override the functionality of the parent class.
views
This can be a simple or complex web page that the controller can call. A webpage can contain a header, footer, sidebar, etc. View cannot be called directly. Let's create a simple view. Create a new file in application/views named " test.php " and copy the code below into this file.
<metacharset="utf-8">
CodeIgniter View Example
Change the application/controllers/test.php file code as shown below.
View loading
The view can be loaded using the following syntax −
$this->load->view('name');
Where name is the view file that is being displayed. If you have planned to store the view file in some directory, you can use the following syntax:
$this->load->view('directory-name/name');
There is no need to specify the extension as php unless something other than .php is being used.
The index() method calls the view method and passes "test" as an argument to the view() method because we have stored the html encoding in the " test.php " file in application/views/test.php .
Here is the output of the above code −
The following block diagram illustrates how everything works −
models
Model classes are designed to work with information in a database. For example, if you are using CodeIgniter to manage users in your application, you should have a model class that contains functions for inserting, deleting, updating, and retrieving your users' data.
Create a Model Class
Model classes are stored in the application/models directory . The following code shows how to create a model class in CodeIgniter.
Where Model_name is the name of the model class you wish to specify. Each model class must inherit the CI_Model CodeIgniter class. The first letter of the model class must be capitalized. Following is the user model class code.
The above model class should be saved as User_model.php. The class name and file name must be the same.
Load Model
The model can be called in the controller. The following code can be used to load any model.
$this->load->model('model_name');
Where model_name is the name of the model to be loaded. Once the model is loaded, you can simply call its method as shown below.
$this->model_name->method();
Autoloading Models
There may be situations where you will need some model class for your entire application. In such situations, it is better if we download it.
/*
| -------------------------------------------------- -------------
| Auto Load Models
| -------------------------------------------------- -------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
As shown in the image above, pass the name of the model in the array you want to load and it will be automatically loaded while the system is in initialization state and available to the entire application.
Helpers
As the name suggests, this will help you build your system. It is divided into small functions to serve different functions. Several helpers are available in CodeIgniter, which are listed in the table below. We can also create our own helpers.
Helpers are usually stored in your system/helpers folder or application/helpers directory . User helpers are stored in the application/helpers directory and system helpers are stored in the system/helpers directory . CodeIgniter will look in your application/helpers directory first . If the directory does not exist or the specified helper is not found, CodeIgniter will instead look in your global system/helpers / directory . Every helper, whether user or system helper, must be loaded before use.
Below are the most commonly used helpers.
SN |
Helper name and description |
one |
Array Helper The Array Helper file contains functions to help you work with arrays. |
2 |
CAPTCHA Helper The CAPTCHA Helper file contains functions that help you create CAPTCHA images. |
3 |
Cookie Helper Cookie Helper contains features to help you manage cookies. |
4 |
date helper The Date Helper file contains functions to help you work with dates. |
5 |
Directory Helper The auxiliary directory file contains functions that help you work with directories. |
6 |
Download Helper Download Helper allows you to download data to your desktop. |
7 |
Email Helper Email Helper provides some helper functions for working with email. For a more robust email solution, see CodeIgniter's Email Class. |
8 |
File Helper The File Helper contains functions to help you work with files. |
9 |
Form Helper The Form Helper file contains functions to help you work with forms. |
10 |
HTML Helper The HTML Helper file contains functions to help you work with HTML. |
11 |
Inflector Helper The Inflector Helper file contains functions that allow you to change words to plural, singular, camel case, etc. |
12 |
Language Helper The Language Helper file contains functions to help you work with language files. |
13 |
Number Assistant The Number Helper file contains functions to help you work with numeric data. |
14 |
Path Helper The Path Helper file contains functions that allow you to work with file paths on the server. |
15 |
Security Assistant The Security Helper file contains security-related functions. |
16 |
Smiley Helper The Smiley Helper file contains functions that allow you to manage smiley faces (emoticons). |
17 |
String Helper The String Helper file contains functions to help you work with strings. |
18 |
Text Assistant The Text Helper file contains functions to help you work with text. |
19 |
Typography Assistant The Typography Helper file contains functions that help format text in semantically relevant ways. |
20 |
URL Helper The URL Helper file contains functions to help you work with URLs. |
21 |
XML Helper The XML Helper file contains functions to help you work with XML data. |
Array Helper
The Array Helper file contains functions to help you work with arrays.
CAPTCHA Helper
The CAPTCHA Helper file contains functions that help you create CAPTCHA images.
Cookie Helper
Cookie Helper contains features to help you manage cookies.
date helper
The Date Helper file contains functions to help you work with dates.
Directory Helper
The auxiliary directory file contains functions that help you work with directories.
Download Helper
Download Helper allows you to download data to your desktop.
Email Helper
Email Helper provides some helper functions for working with email. For a more robust email solution, see CodeIgniter's Email Class.
File Helper
The File Helper contains functions to help you work with files.
Form Helper
The Form Helper file contains functions to help you work with forms.
HTML Helper
The HTML Helper file contains functions to help you work with HTML.
Inflector Helper
The Inflector Helper file contains functions that allow you to change words to plural, singular, camel case, etc.
Language Helper
The Language Helper file contains functions to help you work with language files.
Number Assistant
The Number Helper file contains functions to help you work with numeric data.
Path Helper
The Path Helper file contains functions that allow you to work with file paths on the server.
Security Assistant
The Security Helper file contains security-related functions.
Smiley Helper
The Smiley Helper file contains functions that allow you to manage smiley faces (emoticons).
String Helper
The String Helper file contains functions to help you work with strings.
Text Assistant
The Text Helper file contains functions to help you work with text.
Typography Assistant
The Typography Helper file contains functions that help format text in semantically relevant ways.
URL Helper
The URL Helper file contains functions to help you work with URLs.
XML Helper
The XML Helper file contains functions to help you work with XML data.
Download Assistant
The helper can be downloaded as shown below −
$this->load->helper('name');
Where name is the name of the helper. For example, if you want to download URL Helper, it can be downloaded as −
$this->load->helper('url');
routing
CodeIgniter has a handy URI routing system so you can easily redirect a URL. Typically, there is a one-to-one relationship between a URL string and the corresponding controller class/method. The segments in a URI usually follow this pattern −
your-domain.com/class/method/id/
- The first segment represents the controller class to be called.
- The second segment represents the class function or method to be called.
- The third and any additional segments represent the identifier and any variables that will be passed to the controller.
The first segment represents the controller class to be called.
The second segment represents the class function or method to be called.
The third and any additional segments represent the identifier and any variables that will be passed to the controller.
In some situations, you may want to change this default routing mechanism. CodeIgniter provides a means by which you can set your own routing rules.
Set up routing rules
There is a specific file where you can handle all of this. The file is located at application/config/routes.php. You will find the $route array where you can set up your routing rules. The key in the $route array decides what to route, and the value decides where to route. There are three reserved routes in CodeIgniter.
SN |
Reserved routes and description |
1 |
$route['default_controller'] This route specifies which controller class should be loaded if the URI contains no data, which will be the case when people load your root URL. It is recommended to use the default route, otherwise a 404 page will appear by default. Here we can set the home page of the site to be loaded by default. |
2 |
$route['404_override'] This route specifies which controller class should be loaded if the requested controller is not found. This will override the default 404 error page. This will not affect the show_404() function , which will continue loading the default error_404.php file in application/views/errors/error_404.php . |
3 |
$ route[ "] translate_uri_dashes As you can see from the boolean value, this is not really a route. This option allows you to automatically replace dashes ('-') with underscores in controller and method URI segments, thereby saving additional route entries if you need to do so. This is necessary because the hyphen is not a valid class or method name character and will cause a fatal error if you try to use it. |
$route['default_controller']
This route specifies which controller class should be loaded if the URI contains no data, which will be the case when people load your root URL. It is recommended to use the default route, otherwise a 404 page will appear by default. Here we can set the home page of the site to be loaded by default.
$route['404_override']
This route specifies which controller class should be loaded if the requested controller is not found. This will override the default 404 error page. This will not affect the show_404() function , which will continue loading the default error_404.php file in application/views/errors/error_404.php .
$ route[ "] translate_uri_dashes
As you can see from the boolean value, this is not really a route. This option allows you to automatically replace dashes ('-') with underscores in controller and method URI segments, thereby saving additional route entries if you need to do so. This is necessary because the hyphen is not a valid class or method name character and will cause a fatal error if you try to use it.
Routes can be customized using wildcards or regular expressions, but be aware that these custom routing rules must follow the reserved rules.
Wildcards
We can use two wildcards as described below −
- (:num) - will match a segment containing only numbers.
- (:any) - will match a segment containing any character.
(:num) - will match a segment containing only numbers.
(:any) - will match a segment containing any character.
example
$route['product/:num']='catalog/product_lookup';
In the example above, if the literal word "product" is found in the first segment of the URL, and a number is found in the second segment, the "catalog" class and the "product_lookup" method are used instead.
Regular Expressions
Like wildcards, we can also use regular expressions in the key part of the $route array . If any URI matches the regular expression, it will be redirected to the part of the value specified in the $route array.
example
$route['products/([az]+)/(\d+)']='$1/id_$2';
In the example above, a URI similar to products/shoes/123 would instead call the controller class " shoes " and the method " id_123 ".