tp5参数绑定

关闭路由后的普通模式任然可以通过操作方法的参数绑定、控制器和空操作等特性实现url地址的简化

参数绑定(默认是按名称成对解析,):

namespace app\index\Controller;

class Blog 
{
    public function read($id)
    {
        return 'id='.$id;
    }

    public function archive($year='2016',$month='01')
    {
        return 'year='.$year.'&month='.$month;
    }
}

//上例对应的URL访问地址分别是

http://serverName/index.php/index/blog/read/id/5

http://serverName/index.php/index/blog/archive/year/2016/month/06


输出结果:
id=5
year=2016&month=06

 

按照顺序解析变量需要修改配置文件的url_param_type参数

// 按照顺序解析变量
'url_param_type'    =>  1,

上面的例子修改下访问url地址

//修改url中year和month参数值的顺序
http://serverName/index.php/index/blog/archive/06/2016

输出结果:
year=06&month=2016

按顺序绑定参数,操作方法的参数只能使用URL pathinfo变量,而不能使用get或者post变量

参数绑定有一个特例,操作方法中定义有Request对象作为参数,无论参数位置在哪里,都会自动注入,而不需要进行参数绑定

namespace app\index\Controller;
use think\Request

class Blog 
{
    public function demo1()
    {
        $year=Request:instance()->param('year');
        $month=Request:instance()->param('month');
        $all=Request:instance()->param();//获取全部参数变量
        $get=Request:instance()->get();//获取url?后的参数变量(获取到year变量2018)
        $rt=Request:instance()->route();//获取路径后面的参数变量(只获取到id变量123)
        $post=Request:instance()->post();//获取post参数变量(只获取到age变量18)

    }

    public function demo2(){
        //input获取url变量   同tp3的I()
           $id=input('get.id')
       
    }

    public function demo3(Request $request){
          //依赖注入
           $all=$request->param();
       
    }
}

http://localhost/demo1/123?year=2018(month变量为post传递)

 

架构方法(构造方法)参数绑定(V5.0.1)

当前请求的路由变量可以自动绑定到析构函数的参数,

namespace app\index\Controller;

class Blog 
{
    protected $name;
    public function __construct($name = null)
    {
        $this->name = $name;
    }
}
//如果访问http://localhost/index/index/index/name/thinkphp
//当前请求路由变量name,则thinkphp会自动传入析构方法里的name变量

 

posted @ 2019-02-20 10:39  虚无缥缈的云  阅读(393)  评论(0编辑  收藏  举报