ThinkPHP3.1 Action参数绑定功能介绍
ThinkPHP3.1版本引入了Action参数绑定功能,旨在提供URL变量与操作方法参数之间的直接映射支持。这一机制不仅让操作方法的定义及参数获取过程更加清晰直观,也极大地便利了跨模块的操作方法调用。该新特性完全兼容以往的操作方法使用习惯,开发者可以选择沿用旧方式,也可以利用此特性对现有方法进行重构优化。
Action参数绑定的核心原理是将URL路径中的参数(排除分组、模块及操作名部分)与控制器中具体方法的形参进行对应绑定。以Blog模块为例,其中定义了read和archive两个操作方法:read方法依赖于一个id参数,而archive方法则需要year和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();
}
}
针对上述方法,对应的URL访问地址结构如下:
http://serverName/index.php/Blog/read/id/5
http://serverName/index.php/Blog/archive/year/2012/month/03
在上述两个URL地址中,id参数以及year和month参数会自动与read和archive操作方法中同名的参数完成绑定。 执行后输出的结果依次为:
id=5
year=2012&month=03
需要注意的是,Action参数绑定的前提是参数名称必须与URL传入的参数名称严格一致,但参数的排列顺序无需保持一致。这意味着
http://serverName/index.php/Blog/archive/month/03/year/2012
其访问效果与前述示例完全一致。URL中的参数顺序与方法定义中的参数顺序均可灵活调整,只要确保参数名称匹配即可。 假如用户尝试访问如下URL地址(至于为何如此访问暂不展开):
http://serverName/index.php/Blog/read/
系统将会抛出以下异常提示:
参数错误:id 报错原因十分明确:在执行read操作方法时,id参数被定义为必填项,但方法无法从提供的URL地址中获取有效的id参数信息。鉴于不能盲目信任用户输入,建议为read方法的id参数设置默认值,例如:
public function read($id=0){
echo 'id='.$id;
$Blog = M('Blog');
$Blog->find($id);
}
此时,当我们访问
http://serverName/index.php/Blog/read/
链接时,程序将输出
id=0
若我们访问
http://serverName/index.php/Blog/archive/
链接,则输出:
year=2012&month=01