[PHP] CodeIgniter learning Manual (1): introduction and use of Controller

Source: Internet
Author: User
Tags codeigniter
In short, a controller is a class file and is named in a way that can be associated with a URI. Suppose this URI: example. comindex. phpblog in the above example, CodeIgniter will try to find and load a controller named blog. php. When the Controller name matches the URI

In short, a controller is a class file and is named in a way that can be associated with a URI. Suppose this URI: example.com/index.php/blog/ in the above example, CodeIgniter will try to find and load a controller named blog. php. When the Controller name matches the URI

Brief Introduction to Controller
In short, a controller is a class file and is named in a way that can be associated with a URI.
Assume that the URI:
Example.com/index.php/blog/
In the above example, CodeIgniter will try to find and load a controller named blog. php.
When the Controller name matches the first segment of the URI, it is loaded.

Come to a Hello World!

Let's create a simple controller to learn more about its working principles. Use your text editor to create a file named blog. php and enter the following code:
 


Save the file to the application/controllers/folder.
Use a URL like this to access your website:
Example.com/index.php/blog/
If you are correct, you should see Hello World !.
Note: The class name must start with an uppercase letter. In other words, this is valid:
 

The first letter of the following blog is B in lowercase, which is invalid:

 

At the same time, always make sure that your controller extends from the parent controller class so that it can inherit all its methods.

Meaning of methods in the Controller
The method name used in the preceding example is index (). If the second part of URI is null, the "index" method is loaded by default. You can also write the address as follows to access "Hello World ":
Example.com/index.php/blog/index/

The second part of URI is used to determine the method in the controller.
Let's try again. Add a new method to your controller:
 

Enter the following content in the address bar to access the comments method:
Example.com/index.php/blog/comments/

You should see the new information: Here!


Pass the URI fragment to the Method
If your URI contains more than two parts, more than one is passed as a parameter to the method.
For example, if your URI is as follows:
Example.com/index.php/products/shoes/sandals/123
The 3rd and 4th sections of URI will be passed to your method ("sandals" and "123 "):
 

When calling the above method, two corresponding parameters must be provided, or an error may occur. Of course, you can also write it like below, so you don't have to give parameters during the call!
 

Note: If you use the URI routing feature, the URI segment transmitted to the method will be re-routed once.


Define default Controller
When your website does not have a URI or you directly access it from the root directory, CodeIgniter loads the default controller. Open the application/config/routes. php file to set the default controller:
$route['default_controller'] = 'Blog';

The Blog here is the name of the controller you want to use. If you do not specify any URI fragment to access your home page, the default "Hello World" message is displayed.


Redefinition of method call rules
As mentioned above, the second segment of URI determines which method in the Controller will be called. CodeIgniter allows you to use the _ remap () method to abolish this rule:
public function _remap(){    // Some code here...}

NOTE: If your controller contains a method named _ remap (), it will be ignored no matter what the URI contains. This method will abolish the rule that the URI fragment determines which method is called and allow you to redefine the rule for calling the method (the routing rule of the method ).
The redefined method (usually the second segment in URI) is passed as a parameter to _ remap ():
public function _remap($method){    if ($method == 'some_method')    {        $this->$method();    }    else    {        $this->comments();    }}

Any segment appended with the method name will be treated as the second parameter of _ remap () (optional ). This optional array parameter can be used with PHP call_user_func_array to simulate the default behavior of CodeIgniter.
public function _remap($method, $params = array()){    $method = 'process_'.$method;    if (method_exists($this, $method))    {        return call_user_func_array(array($this, $method), $params);    }    show_404();}


Processing output
CodeIgniter has an output class to ensure that the modified data is automatically transmitted to the browser. More information about this can be found in the view and output class. Sometimes, you may want to publish and modify the final data or pass it to your browser. CodeIgniter allows you to add a method named _ output () to your controller to receive the final data.
NOTE: If your controller contains a _ output () method, it will always be called instead of directly outputting final data. This method is similar to the destructor in OO. Whether you call any method, this method will always be executed.
For example:
public function _output($output){    echo $output;}

Note that your _ output () will receive the final data. Benchmark and memory usage data will be rendered, cached files will be written (if cache is enabled), and HTTP headers will also be sent (if you use this function ), then, it is handed over to the _ output () function.

To make your controller output cache correct, its _ output () function can be written as follows:
if ($this->output->cache_expiration > 0){    $this->output->_write_cache($output);} 

If you are using the page execution time and memory usage statistics function, this may not be completely accurate because they will not take into account any further actions you have done. Use available methods to control the output before any final process is completed.


Private Method

In some cases, you may want to hide some methods to make them unavailable. It is easy to privatize a method. You only need to prefix the method name with an underscore ("_") and cannot access the method through the URL. For example, if you have a method like this:
private function _utility(){  // some code}

The following URL cannot be accessed:

Example.com/index.php/blog/_utility/



How to put controllers in subfolders

If you create a large application, you will find that CodeIgniter can easily put the Controller in some subfolders.
You only need to create a folder in the application/controllers directory and put it in your controller.
Note: If you want to use the functions in a sub-folder, make sure that the first segment of the URI is used to describe the folder. For example, you have a controller here:
Application/controllers/products/shoes. php
When calling this controller, your URI should be written as follows:
Example.com/index.php/products/shoes/show/123

Each of your subfolders needs to contain a default controller, so that it will be called if the URI contains only subfolders and has no specific functions. You only need to specify the default controller name in the application/config/routes. php file.

CodeIgniter also allows you to use the URI routing function to redirect the URI.



Constructor
If you want to use constructors in any of your controllers, you must add the following line of code:
Parent: :__ construct ();
The necessity of this line of code is that your constructor here will overwrite the constructor in the parent controller class, so we need to call it manually.
 

If you need to set some default values or run a default program during class instantiation, constructors are very useful in this regard.
Constructors do not return values, but can be used to set some default functions.
Reserved method name

Because the Controller class you added inherits the main application controller, you must be careful not to use the same method name as the method name in the class, otherwise, your method will overwrite the original one. For more information, see reserved words.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.