Generally speaking, the thinkphp controller is a class, and the operation is a public method of the Controller class. Let's talk a little more about Thinkphp's controller.
In the previous lesson, you might have a hint of confusion about the route to thinkphp, but it's okay to learn a lot from this course.
Controller file naming follows IndexController.class.php
Definition of the Controller
Before we get started, we need to make a clear definition of the controller:
<?phpnamespace 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 chapter is defined as:
Using the appropriate namespace, the default is namespace Home\controller
Load Think\controller
New controllers inherit from controller (or subclass)
Use the Hump naming method, pay attention to the first letter capitalization
Public methods within the controller can be thought of as an operation, such as the Read () and Top () methods above, which we have verified in the routing chapter.
Http://localhost:8999/index.php/Home/Index/top
is to access the top () method, the page will be printed on the top page, again clear home represents the home module
Sometimes you may encounter a method that conflicts with a system keyword, which can be resolved by using the Set operation method suffix.
Pre-and post-operation
Pre-and post-operation refers to methods that are called automatically before and after an action method is executed, but only for access controllers, 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 will see the print out:
Before top pagetop pageafter top page
There are two points to note when using front and rear operations:
If the current operation does not define an action method, but rather renders the template file directly, it will still take effect if the pre-and post-method is defined. The actual template output may be just the current operation, and the front and rear operations generally do not have any output.
It is important to note that there are some ways to use Exit or error output and so on, it is possible that the post-placement method will not be executed. For example, if the error method of the system action is called in the current operation, then the post operation is no longer performed, but the post-method execution of the success method is not affected
Can be used for filtering and validation of forms
Parameter binding
Parameter binding simplifies the definition of a method or even the parsing of a route by directly binding a variable in the URL address as a parameter to the action method.
' 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 parameters: Bind by variable name and bind by variable order, by default it is bound 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 settings that were previously routed
' Blogs/:id ' = = Array (' Index/read ')
We will: the ID directly mapped 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 it 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, simply pass in the corresponding variable name and value, 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
It is important to note that, regardless of the circumstances, when you visit
http://localhost:8999/index.php/Home/index/read/
will be an error:
parameter is wrong or undefined: ID
A good way to solve this is to set the default values for the binding parameters, such as:
Public function read ($id =0) { echo ' read page with </br> '. $id; }
This again accesses the above URL and outputs:
Read page with
0
Tips: Setting default values for binding parameters is a good way to avoid errors
In actual development, we actually met with URLs that did not show variable names 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 first need to set it in the settings:
' Url_params_bind_type ' = 1
Once you set the variable order binding, in this case the order of the parameters in the URL address is very important and cannot be arbitrarily adjusted. In this case, the definition of the operation method does not need to change, but the URL of the access is changed, and now access by the above method can be accessed correctly.
If, in the case of variable order binding, 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 not the same, 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 parameter arbitrarily at the end of the URL to add the static suffix you want, without affecting the normal execution of the current operation, by default, Pseudo-Static is set to HTML. But we can set ourselves, 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, it means that all static suffixes can be supported.
You can also set the Forbidden 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 generate the corresponding URL address according to the current URL settings, for this reason, thinkphp built-in provides a U method for the dynamic generation of URLs to ensure that the project is not affected by the environment during the migration process.
Defining rules
The definition rules for the U method are as follows (the parameters in square brackets are determined according to the actual application):
U (' address expression ', [' parameter '],[' pseudo static suffix '],[' Display domain name '])
Address expression
The format of an address expression is defined as follows:
[module/Controller/Operation # Anchor point @ domain name]? parameter 1= value 1& parameter 2= value 2 ...
If you do not define a module, it represents the current module name, here are some simple examples:
U (' user/add ')//generate the URL address of the User controller's add operation
U (' article/read?id=1 ')//Generate a read operation for the article controller and a URL address with ID 1
U (' admin/user/select ')//URL address of the select operation of the User controller generating the Admin module
Parameters
The second parameter of the U method supports both the array and the string definitions, if only a string-like argument 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 methods are equivalent, all of which generate the Cate () operation of the article controller and a URL address of cate_id of 1 status 1
However, it is not allowed to use the following definition 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 as:
' 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 commonly used features in development. In application development, you will often encounter a number of jump pages with hints, such as the success of the operation or the error page, and automatically jump to another target page. The \think\controller class of the system contains two jump methods success () and error () for page jump hints.
Jump
The use of the method is very simple, for example, we create a new method under the Index controller user (), 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 ') 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 in it.
<?phpnamespace home\controller;use Think\controller;class Usercontroller extends Controller {public function AddUser () { echo ' Add user done! '; }}
Then access the Http://localhost:8999/Home/Index/user in the browser, you can see the add user done!, in detail, the following two redirection methods.
The first parameter of the success () and the error () method represents the prompt message, the second parameter represents the jump address, and the third parameter is the jump time in seconds, for example:
REDIRECT To/article/index after 3 seconds if 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 two jump addresses above with home/home, if you want to shorthand for/article/index, you need to add the following line to the thinkphp Portal file (index.php in the project directory):
Define (' Bind_module ', ' Home ');
And both methods have a 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 page redirection.
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 stop 3 seconds after jumping to the article Controller's show () operation, and display the page jump in the word 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 was an article Page '; $id variables We will 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 simply want to redirect to a specified URL address instead of to a module, you can use the redirect () function redirection 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 URL rule defines the jump address, which is a purely URL address
Note: It seems like the official documents are written like this
$this->redirect ('/NEW/CATEGORY/CATE_ID/2 ', 5, ' page jump ... ');
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!