ThinkPHP Controller Details

Source: Internet
Author: User
Generally, the controller of ThinkPHP is a class, while the operation is a public method of the controller class. Next, let's talk about the ThinkPHP controller in detail. in the last course, you may have some questions about ThinkPHP routing. but it doesn't matter. after learning this course, many ThinkPHP controllers will suddenly become open.

The controller file name follows the IndexController. class. php method.

Controller definition

Before starting, we still need to clarify the definition of the controller:

<?phpnamespace Home\Controller;use Think\Controller;class IndexController extends Controller {  public function read($id){    echo "read page with 
" .$id; } public function top(){ echo "top page
"; }}

As you can see, the controller mentioned in the routing section is defined as follows:

Use the corresponding namespace. the default namespace is Home \ Controller.
Load Think \ Controller
The new Controller inherits from the Controller (or subclass)
The hump naming method is used. Note that the first letter is capitalized.
The public methods in the controller can be regarded as an operation. for example, the read () and top () methods above can be regarded as operations. we have verified them in the routing article.

Http: // localhost: 8999/index. php/Home/Index/top
Is to access the top () method, the top page will be printed on the page, and again it is clear that Home represents the Home module

Sometimes there may be conflicting methods with system keywords. in this case, you can use the suffix of the operation method to solve the problem. for details, see the official documentation:
Http://document.thinkphp1.cn/manual_3_2.html#define_controller

Front and back operations

Pre-and post-Operations refer to methods that are automatically called before and after an operation method is executed. However, they are only valid for the access controller, for example, top () in IndexController () method to add the pre-post method:

public function _before_top(){    echo "before top page 
"; } public function top(){ echo "top page
"; } public function _after_top(){ echo "after top page
"; }

Access: http: // localhost: 8999/index. php/Home/Index/top

The output is as follows:

before top pagetop pageafter top page

Note the following before and after operations:

If the current operation does not define the operation method, but directly renders the template file, it will still take effect if the pre-and post-methods are defined. The real template output may only be the current operation. the front and back operations generally do not have any output.

Note that if exit or error output is used in some methods, the Post method may not be executed. For example, if the system Action error method is called in the current operation, the Post operation will not be executed, but the execution of the Post method of the success method will not be affected.

It can be used for form filtering and verification.

Parameter binding

Parameter binding directly binds the variables in the URL address as the parameters of the operation method, which can simplify the definition of the method and even parse the route.

'URL_PARAMS_BIND'    => true


The parameter binding function is enabled by default. The principle is to bind parameters (excluding modules, controllers, and Operation names) in the URL to parameters in the operation method.
There are two ways to bind parameters: bind according to the variable name and bind according to the variable order. by default, bind according to the variable name. for example, see the following example:

 public function read($id){    echo "read page with 
".$id; } public function archive($year, $month){ echo "$year
".$month; }

Yes, this is the content of the previous route.

'Blogs/: ID' => array ('index/read ')
We map the id directly to the $ id parameter of the read () method, so now let's look back. In fact, the routing rule gives you a custom URL function. If the preceding route settings are removed, the correct access method is:

Http: // localhost: 8999/Home/index/read/id/3

In the above URl, id is the variable name. if you write it:

 public function read($title){    echo "read page with 
".$title; }

The access address is:

Http: // localhost: 8999/index. php/Home/index/read/title/3

When multiple parameters are bound, only the corresponding variable names and values can be passed in, regardless of the order. for example, the following two will return the same result:

Http: // localhost: 8999/index. php/Home/index/archive/year/2012/month/12

Http: // localhost: 8999/index. php/Home/index/archive/month/12/year/2012

It should be noted that, in any case, when you access

Http: // localhost: 8999/index. php/Home/index/read/
Yes, an error is reported:

Parameter error or undefined: id
A good solution is to set the default value for the bound parameter, for example:

 public function read($id=0){    echo "read page with 
".$id; }

In this way, the above URL will be accessed again and the output will be:

Read page
0

Tips: setting default values for binding parameters is a good way to avoid errors.
In actual development, we will see no URLs with variable names, such:

Http: // localhost: 8999/index. php/Home/index/read/3

How can this problem be solved? In this case, we can actually use the second parameter binding: variable binding. To bind this parameter, you must first set it in the settings:

'URL_PARAMS_BIND_TYPE' => 1

Once variable order binding is set, the parameter order in the URL address is very important and cannot be adjusted at will. In this case, the definition of the operation method does not need to be changed, but the access URL has changed. now, you can access the method correctly.

If the variable order is bound, we access:

Http: /localhost: 8999/index. php/Home/index/archive/2012/12

Http: /localhost: 8999/index. php/Home/index/archive/12/2012

The two results are obviously different. The latter is not what we want. Therefore, values must be transmitted in strict order.

Pseudo-static

The URL pseudo-static is usually used to achieve better SEO performance. ThinkPHP supports pseudo-static URL settings. you can add the desired static suffix at the end of the URL by setting the URL_HTML_SUFFIX parameter, the normal execution of the current operation is not affected. by default, the pseudo-static settings are html. But we can set it by ourselves, for example

'URL _ HTML_SUFFIX '=> 'shtml'

If you want to support multiple pseudo-static suffixes, you can directly set them as follows:

'URL _ HTML_SUFFIX '=> 'HTML | shtml | XML'

If this setting is left blank, all static suffixes are supported.

You can also set the URL suffix of the forbidden access through URL_DENY_SUFFIX. for example:

'URL _ DENY_SUFFIX '=> 'PDF | ico | png | gif | jpg ',
Note: URL_DENY_SUFFIX has a higher priority than URL_HTML_SUFFIX.

URL generation

To work with the URL mode, we need to be able to dynamically generate the corresponding URL address based on the current URL settings. For this reason, ThinkPHP provides a built-in U method for dynamic URL generation, this ensures that the project is not affected by the environment during the migration process.

Define rules

The U method is defined as follows (parameters in square brackets are determined based on actual application ):
U ('address expression', ['parameter'], ['pseudo-static suffixes '], ['display domain name'])

Address expression

The format of an address expression is defined as follows:

[Module/controller/Operation # anchor @ domain name]? Parameter 1 = value 1 & parameter 2 = value 2...
If no module is defined, it indicates the current module name. Below are some simple examples:

U ('user/add') // Generate the URL of the add operation of the User controller
U ('Article/read? Id = 1') // Generate the URL address of the read operation of the Article controller with id 1
U ('admin/User/select') // Generate the URL of the select operation of the User controller of the Admin module

Parameters

The second parameter of the U method supports two definition methods: Array and string. if the parameter is just a string, it can be defined in the first parameter, for example:

U('Article/cate',array('cate_id'=>1,'status'=>1))U('Article/cate','cate_id=1&status=1')U('Article/cate?cate_id=1&status=1')

The three methods are equivalent. they are URL addresses that generate the cate () operation of the Article controller and the cate_id is 1 and the status is 1.

However, the following definition is not allowed to pass parameters:

U('Article/cate/cate_id/1/status/1');

Generate route address

The U method can also support routing. if we define a routing rule:

'blogs/:id\d'=>'Index/read'

You can use

U('/blogs/1');

The generated URL is:

Http: // localhost: 8999/index. php/Home/blogs/1

Redirect and redirect

This should be one of the most common features in development. During application development, you will often encounter jump pages with prompts, such as pages with Operation successes or operation errors, and automatically jump to another target page. The \ Think \ Controller class of the system has two built-in jump methods success () and error () for page jump prompts.

Jump

The usage method is simple. for example, we create a user () method under the Index controller and write the following content:

public function user()  {    $User = M('User');    $data['username'] = 'Think';    $data['email'] = 'Think@gmail.com';    $result = $User->add($data);    if($result){      $this->success('success', '/Home/User/addUser');    } else {      $this->error('failed');    }  }

M ('user') indicates instantiating a User object. the add () method adds a record to the database. Then we need to create a new UserController and write the addUser () method in it.

<?phpnamespace Home\Controller;use Think\Controller;class UserController extends Controller {  public function addUser()  {    echo 'add user done!';  }}

Access http: // localhost: 8999/Home/Index/user in the browser and you will see add user done! These two redirection methods are described in detail below.

The first parameter of the success () and error () methods indicates the prompt information, the second parameter indicates the jump address, and the third parameter indicates the jump time (in seconds). For example:

// redirect to /Article/index after 3 seconds when success$this->success('done','/Home/Article/index',3);// redirect to /Article/error after 5 seconds when failed$this->error('failed','/Home/Article/error',5);

If no jump time is set, the default wait time success () method is 1 second, and the error () method is 3 seconds. The above two jump addresses are preceded by/Home. if you want to abbreviated it as/Article/index, you need to go to the ThinkPHP entry File (index under the Project Directory. php) add a line above and below:

define('BIND_MODULE','Home');

Both methods have corresponding templates. the default settings are as follows:

'Tmpl _ ACTION_ERROR '=> THINK_PATH. 'tpl/dispatch_jump.tpl ',

'Tmpl _ ACTION_SUCCESS '=> THINK_PATH. 'tpl/dispatch_jump.tpl ',
You can modify the template as needed.

Redirection

The redirect () method of the Controller class can implement page redirection.
The parameter usage of the redirect () method is the same as that of the U function (refer to the URL generation section in the previous section), for example:

$ This-> redirect ('/Home/Article/Show', array ('id' => 2), 3, 'redirecting ...');
The above usage is to jump to the show () operation of the Article controller after 3 seconds, and display the Redirecting... in the page jump. after the redirection, the current URL address will be changed.

To perform the test successfully, add the redirectToArticle () method under IndexController and write the above line of code:

public function redirectToArticle()  {    $this->redirect('/Home/Article/show', array('id' => 2), 3, 'Redirecting...');  }

Then we create an ArticleController and add the show () method to it:

Namespace Home \ Controller; use Think \ Controller; class ArticleController extends Controller {public function show ($ id) {echo 'This is an Article page '; // $ id variable will be used later. now it is just a demo jump }}

Then visit: http: // localhost: 8999/Home/Index/redirectToArticle in the browser. wait for three seconds and you will see the page after the jump.

If you only want to redirect to a specified URL address, rather than the operation method to a module, you can directly use the redirect () function to redirect, such

$ This-> redirect ('/Home/Article/show/id/3', 'redirecting...', 3 );

Note: the difference between the controller's redirect () method and redirect () function is that the former uses URL rules to define the jump address, and the latter is a pure URL address.
Note: It seems that the official document is written in this way.

$ This-> redirect ('/New/category/cate_id/2', 5,' page jump ...');

The above is all the content of this article. I hope you will like it.

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.