Thinkphp请求和响应

406 阅读1分钟

请求和响应

1. 请求对象获取

三种方式

  • 助手函数 request() : $re = request();
  • Rquest类instance() : use think\Request; $re = Request::instance();
  • 注入对象 :use think\Request; 方法参数注入Request对象
<?php
namespace app\index\controller;
use think\Request;
class Index
{
    public function index(Request $request)
    {
//        $request = request();
//        $request = Request::instance();
        dump($request);
    }
}

2. 请求对象参数获取

 dump($request->domain());
        dump($request->pathinfo());
        dump($request->path());
        
        #请求类型
        dump($request->method());
        dump($request->isGet());
        dump($request->isPost());
        dump($request->isAjax());

        #获取请求的参数
        dump($request->get());
        dump($request->param());
        dump($request->post());
        //session('name','sunxiaopeng');
        dump($request->session());
        cookie('email','sunxiaopeng@163.com');
        dump($request->cookie());
        dump($request->param('type'));
        dump($request->cookie('email'));

      
        #获取模块 控制器 和操作
        dump($request->module());
        dump($request->controller());
        dump($request->action());
        dump($request->url());
        dump($request->baseUrl());

3. 助手函数input

1、input助手函数也是获取对象里面的参数. input('传递方式','参数','对参数过滤')

注意获取请求的参数值,尽可能带上请求的方式,如:input(get.id) ,如果获取的值不存在时,可通过第二个值进行默认值设置,第三个值用来过滤获取的值,例如可将值转换成intval

2、同时也可以通过request对象下的相关方法获取对应的参数或值,来对值进行相关操作

<?php
namespace app\index\controller;
use think\Request;
class Index{
public function index(Request $request){
//dump($request->param());//param方法会返回post,get,pathinfo传递的所有值,即合并
//http://localhost/imooc/public/index/index/index/type/5.html?id=10 
//$res = input('get.id');//10
//dump($request->get('id'));//10
//$res = input('post.id','100');//没有则默认100,结果100
//dump($request->post('id','100'));//100
//$res = input('post.id','abc','intval');//没有则默认100,结果100
//dump($request->post('id','100'));//100****
#获取类型
//'get''post',
//'put''patch',
//'delete''param',
//'request''session',
//'cookie''server',
//'env''path''file'
//通过input助手函数对request中参数进行获取,#建议使用request对象(Request $request)#,避免重复定义相同函数
//$res = input('patch.id');
//session('emial','987@qq.com');
//dump(input('session.emial'));
//dump(input('session.emials','imooc@qq.com'));
//不存在默认imooc
session('ss','   123   ');
$res = $request->session('ss','','trim');//trim过滤前后空格
dump($res);
}
}

4.响应对象

1.针对某一个模块返回其他格式类型,那么需要给在conf文件中创建对应模块的配置文件config.php中配置default_return_type

2.针对某一个操作返回特殊的类型,那么可以通过动态配置实现

在TP5中不允许在控制器和方法里die(),因为响应有可能发生问题

一般在控制器里面直接return 数据,默认格式为html,默认会调用response对象出输出数据,如果需要对数据格式进行修改,第一种在config.php中修改,这个设置全局的,如果想对某个控制器的数据进行修改,一般在控制器里面动态设置返回格式

动态配置返回类型为json,用Config::set('default_return_type', 'json');