Action Parameter Binding for ThinkPHP 3.1 New Feature
- 2021-07-01 06:46:53
- OfStack
The Action parameter binding function of ThinkPHP version 3.1 provides parameter binding support for URL variables and operation methods. This function can make your operation method definition and parameter acquisition clearer, and it is also convenient to call operation methods across modules. This new feature has no effect on the previous operation method use, and you can also modify the previous operation method definition in a new way.
The principle of Action parameter binding is to bind the parameters in URL (excluding grouping, module and operation address) with the parameters in the operation method of the controller. For example, we define two operation methods read and archive for Blog module. Because read operation needs to specify one id parameter, archive method needs to specify two parameters: year (year) and month (month).
class BlogAction extends Action{
public function read($id){
echo 'id='.$id;
$Blog = M('Blog');
$Blog->find($id);
}
public function archive($year='2012',$month='01'){
echo 'year='.$year.'&month='.$month;
$Blog = M('Blog');
$year = $year;
$month = $month;
$begin_time = strtotime($year . $month . "01");
$end_time = strtotime("+1 month", $begin_time);
$map['create_time'] = array(array('gt',$begin_time),array('lt',$end_time));
$map['status'] = 1;
$list = $Blog->where($map)->select();
}
}
The access addresses of URL are:
http://serverName/index.php/Blog/read/id/5
http://serverName/index.php/Blog/archive/year/2012/month/03
The id and year and month parameters in the two URL addresses are automatically bound to the same name parameters of the read operation method and the archive operation method.
The output results are as follows:
id=5
year=2012&month=03
The Action parameter must be bound with the parameter name 1 passed in URL, but the parameter order does not need to be 1. That is to say
http://serverName/index.php/Blog/archive/month/03/year/2012
And the above access result is 1, the parameter order in URL and the parameter order in the operation method can be adjusted at will, and the key is to ensure that the parameter name is 1.
If the URL address accessed by the user is (let's not mention why it is so accessed):
http://serverName/index.php/Blog/read/
The following exception prompt will be thrown:
Parameter error: id
The reason for the error is simple, because the id parameter must be passed in when executing the read operation method, but the method cannot get the correct id parameter information from the URL address. Since we can't trust any input from the user, we recommend that you add default values to the id parameter of the read method, such as:
public function read($id=0){
echo 'id='.$id;
$Blog = M('Blog');
$Blog->find($id);
}
So, when we visit
http://serverName/index.php/Blog/read/
Will output when
id=0
When we visit
http://serverName/index.php/Blog/archive/
Output:
year=2012&month=01