thinkphp Controller Detailed _php skills

Source: Internet
Author: User

In the previous lesson, you might have a bit of a problem with the routing of thinkphp, but never mind, with this course, a lot of things will suddenly come to an end.

Controller file naming follow the IndexController.class.php way

The definition of the controller

Before we begin, we need to be clear about the definition of the controller:

<?php
namespace Home\controller;
Use Think\controller;
Class Indexcontroller extends Controller {public

  function read ($id) {
    echo ' read page with </br> '. $id; 
   
    } public

  function top () {
    echo ' top page </br> ';
  }

}


   

As you can see, the controller mentioned earlier in the routing article is defined as this:

Using the appropriate namespace, the default is namespace Home\controller
Load Think\controller
New controller inherits from controller (or subclass)
Using the Hump nomenclature, note the first letter capital
Public methods within the controller can be considered as an operation, such as the Read () and Top () methods above can be regarded as operations, and we have validated them in the routing chapter.

Http://localhost:8999/index.php/Home/Index/top
is to access the top () method, and then print out the upper page on the page and again make it clear that home is the home module.

Sometimes you may encounter a system-specific keyword conflict method, which can be resolved by using the Set action method suffix, see the official documentation:
Http://document.thinkphp.cn/manual_3_2.html

Predecessors and post operations

A predecessor and a post operation refers to a method that is called automatically before and after an action method is executed, but is only valid for the access controller, such as adding a predecessor method to the top () method in Indexcontroller:

Public Function _before_top () {
    echo ' before top page </br> ';
  }
  Public Function Top () {
    echo ' top page </br> ';
  }
  Public Function _after_top () {
    echo ' after top page </br> ';
  }

Visit: Http://localhost:8999/index.php/Home/Index/top

You'll see the print out:

Before top page top page

Use the front and back actions to note the following two points:

If the current operation does not define an action method, but instead renders the template file directly, it will still take effect if the predecessor and post methods are defined. The actual template output may be just the current operation, and the predecessor and post operations generally do not have any output.

It should be noted that there are some methods where exit or error output is used, and it is possible that the Post method will not be executed again. For example, if the system action error method is invoked in the current operation, the post operation will no longer be performed, but it does not affect the success method execution

Can be used for filtering and validation of forms

Parameter bindings

A parameter binding is a parameter that directly binds a variable in a URL address as an action method, which simplifies the definition of a method or even the parsing of a route.

' Url_params_bind '    => True


The parameter binding feature is turned on by default, and the principle is to bind the parameters in the URL (excluding modules, controllers, and operation names) and the parameters in the action method.
There are two ways to bind a parameter: By binding the variable name and binding in the order of the variables, the default is to bind by variable name, for example, see the following example:

 Public function Read ($id) {
    echo ' read page with </br> '. $id;
  }

 Public Function Archive ($year, $month) {
    echo $year </br>. $month;
  }

Yes, this is what the previous route involved, in the route setup that was previously routed

' Blogs/:id ' => array (' Index/read ')
We will: ID directly map to the read () method parameter $id, so now look back, in fact, the routing rule is to give you a custom URL function. If you remove the above routing settings, the correct way to access them is:

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

The ID in the URL above is the variable name, if you write:

 Public function Read ($title) {
    echo ' read page with </br> '. $title;
  }



Then the access address is:

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

For multiple parameter bindings, just pass in the appropriate variable names and values, regardless of the order, such as 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

Note that regardless of that situation, when you visit

http://localhost:8999/index.php/Home/index/read/
There will be an error:

Parameter error or undefined: ID
A good way to fix this is to set a default value for the parameters of the binding, such as:

 Public function read ($id =0) {
    echo ' read page with </br> '. $id;
  }

This accesses the above URL again, and the output is:

Read page with
0

Tips: Setting default values for binding parameters is a good way to avoid errors
In actual development, we actually met a URL that did not display the variable name, such as:

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

How to solve it? At this point, we can actually use the second parameter binding: Binding in the order of the variables. To use this parameter binding, you need to set it in the Settings key first:

' Url_params_bind_type ' => 1

Once you set the variable order bindings, the order of the parameters in the URL address is very important in this case and cannot be adjusted arbitrarily. In this case, the definition of the operation method does not need to be changed, just the URL of the access changed, and now access to the way the above can be accessed correctly.

If the variables are bound in order, we access:

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

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

These two results are obviously different, and the latter is not what we want. So this situation requires strict adherence to the order to pass the value.

Pseudo static

URL pseudo-static is usually to meet the better SEO effect, thinkphp support pseudo static URL settings, you can set the Url_html_suffix parameters at random at the end of the URL to increase the static suffix you want, and will not affect the normal operation of the current operations, by default, Pseudo-Static is set to HTML. But we can set ourselves up, for example

' Url_html_suffix ' => ' shtml '

If you want to support multiple pseudo static suffixes, you can set the following directly:

' Url_html_suffix ' => ' html|shtml|xml '

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

You can also set a blocked URL suffix to be set by Url_deny_suffix, for example:

' Url_deny_suffix ' => ' pdf|ico|png|gif|jpg ',
Note: Url_deny_suffix priority is higher than url_html_suffix.

URL generation

In order to match the URL pattern used, we need to be able to dynamically based on the current URL settings to generate the corresponding URL address, for this reason, thinkphp built-in U method for the dynamic generation of URLs, to ensure that the project in the migration process is not affected by the environment.

Defining rules

The definition rules for the U method are as follows (in square brackets the parameters are determined according to actual application):
U (' address expression ', [' parameter '],[' pseudo static suffix '],[' Display domain name '])

An 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 you do not define a module to represent the current module name, here are some simple examples:

U (' user/add ')//Generate URL address of add operation for User Controller
U (' article/read?id=1 ')//Generate Article Controller's read operation and URL address with ID 1
U (' admin/user/select ')//The URL address of the select operation of the User controller that generates the Admin module

Parameters

The second parameter of the U method supports two definitions of array and string, if only the argument in string mode 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 ')


Three ways are equivalent to generating the Cate () operation of the article controller and cate_id to the URL address of 1 status 1

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

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

Generate Routing Address

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

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

Then you can use

U ('/blogs/1 ');

The resulting URL address is:

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

Jump and redirect

This should be one of the most common features in development. In application development, you will often encounter a number of jump pages with hints, such as the successful operation or the operation of the error page, and automatically jump to another target page. The system's \think\controller class is built with two jump methods success () and error () for page jump prompts.

Jump

The use method is simple, for example, we create a new method user () under the index controller, and write the following:

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

M (' user ') represents the instantiation of a User object, and the Add () method adds a record to the database. Then we need to create a new Usercontroller and write the AddUser () method inside it.

<?php
namespace Home\controller;

Use Think\controller;

Class Usercontroller extends Controller {public

  function AddUser ()
  {
    echo ' Add user done! ';
  }
}

Then you can access Http://localhost:8999/Home/Index/user in the browser and you will see Add User done!, which is described in detail in the following two redirection methods.

The first parameter of the success () and error () method represents the prompt, the second parameter represents the jump address, and the third parameter is the jump time (in seconds), for example:

REDIRECT To/article/index after the 3 seconds when the 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 you do not set the jump time, the default wait Time success () method is 1 seconds, and the error () method is 3 seconds. See the above two jump addresses with/home, if you want to/article/index, you need to add the following line to the Thinkphp entry file (index.php in the project directory):

Define (' Bind_module ', ' home ');

And both methods have the corresponding template, the default setting is two methods corresponding to the template are:

' Tmpl_action_error ' => think_path. ' Tpl/dispatch_jump.tpl ',

' Tmpl_action_success ' => think_path. ' Tpl/dispatch_jump.tpl ',
You can modify the template according to your own needs.

redirect

The redirect () method of the Controller class enables the redirection of pages.
The parameter usage of the redirect () method is consistent with the use of the U function (refer to the previous part of the URL Generation section), for example:

$this->redirect ('/home/article/show ', array (' ID ' => 2), 3, ' redirecting ... ');
The above usage is to stay 3 seconds to jump to the article Controller show () operation, and display the page jump redirecting ..., redirect will change the current URL address.

To successfully test, we 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 a articlecontroller and add the show () method to him:

namespace Home\controller;

Use Think\controller;

Class Articlecontroller extends Controller {public

  function Show ($id)
  {echo ' This is a
    Article Page '; 
   //$id Variable We'll use later, now just demo jump
  }
}

Then in the browser access: http://localhost:8999/Home/Index/redirectToArticle, wait three seconds, you can see the page after the jump.

If you just want to redirect to a specified URL address, rather than to a module's action method, you can use the redirect () function redirect directly, for example

$this->redirect ('/home/article/show/id/3 ', ' redirecting ... ', 3);

Note: The difference between the redirect () method of the controller and the redirect () function is that the former is defined as a jump address with a URL rule, which is a pure URL address
Note: It seems the official document is written like this

$this->redirect ('/NEW/CATEGORY/CATE_ID/2 ', 5, ' page jump ... ');

The above mentioned is the entire content of this article, I hope you can enjoy.

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.