ThinkPHP5.0.11Day03:Request对象,Session和Cookie,判断请求类型,方法注册,Response(json xml jsonp)

目录

0x00 Request对象:

增加默认值的功能:

不接收某些字段:

0x01 session 和cookie的配置以及获取

0x02判断请求类型:

0x03方法注册

0x04Response


0x00 Request对象:

原生php开发中的超全局变量数组$_GET,$_POST,$_REQUEST,$_SERVER,$_SESSION,$_COOKIE,$_ENV等,在ThinkPhp中都被封装在了Request对象中;

方法 描述
param 获取所有类型的请求的变量
get 获取$_GET变量
post 获取$_POST变量
put 获取PUT变量
delete 获取delete变量
session 获取$_SESSION变量
cookie

获取$_COOKIE变量

request 获取$_REQUEST变量
server 获取$_SERVER变量
env 获取$_ENV变量
route 获取路由(包括PATHINFO)变量
file 获取$_FILE变量

演示:

param()方法是框架提供的自动识别get post put请求的一种变量获取方法,是tp框架推荐的获取请求参数的方法。

router.php:

Route::get('admin/:id','admin/index/index');

admin/index.php class index中增加index方法

public function index(Request $request){
        return 'hello world'.$request->param('id');
    }

相当于:

public function index(){
        $request = Request::instance();
        return 'hello world'.$request->param('id');
    }

访问:

方法二:使用助手函数

request()

 public function index(Request $request){
        // return 'hello world'.$request->param('id');
        return 'hello world'.request()->param('id');
    }

input()

 public function index(Request $request){
        // return 'hello world'.$request->param('id');
        // return 'hello world'.request()->param('id');
         return 'hello world'.input('id');
    }

调用关系:input() 调用request()调用Request::instance()

增加默认值的功能:

修改router.php

Route::get('admin/[:id]','admin/index/index');

加一个中括号表示参数可有可无

修改index.php

   public function index(Request $request){
        return 'hello world'.$request->param('id','1234567');
    }

给id一个默认参数,当没有get传参的时候,就会用默认参数。

不接收某些字段:

public function index_post(Request $request){
        dump("this is post");
        dump($request->except('email'));
    }

表示除了email字段,其余的post传参都接受,返回值是一个数组。如果想排除多个,用逗号隔开即可,例如'email,id'

接受所有post传参,返回值是一个数组,几乎和$_POST一模一样。

public function index_post(Request $request){
        dump("this is post");
        dump($request->param());
    }

只获取某些字段:返回值是一个数组

public function index_post(Request $request){
        dump("this is post");
        dump($request->only('email,name'));
    }

获取值加函数过滤

 public function index_post(Request $request){
        dump("this is post");
        return $request->param('email','',"htmlspecialchars");
    }

注意:

1.第二个值是传参的默认值,如果没有默认值,需要用‘’将这个参数给空出来。

2.如果有多个函数,用逗号隔开即可。任何函数都可以加。

3.config.php文件中可以配置默认的全局过滤方法,可以将htmlspecialchars直接加在这里。

补充:strip_tags和htmlspecialchars的区别:前者是将html标签直接去除,后者将html标签转化为字符实体。

0x01 session 和cookie的配置以及获取

route.php

Route::get('setSess','index/index/setSess');
Route::get('getSess','index/index/getSess');
Route::get('unsetSess','index/index/unsetSess');

use think\Session

设置Session

    public function setSess(){
        Session::set('username','xiaoshang');
    }

相当于:session_start() + $_SESSION['username']='xiaoming'

获取Session的值

    public function getSess(Request $request){
        dump($request->session('username'));
    

删除Session

    public function unsetSess(){
        Session::set('username',null);
    }

等价于:session_start() + $_SESSION['username']=null

关于Cookie

route.php

Route::get('setCookie','index/index/setCookie');
Route::get('getCookie','index/index/getCookie');
Route::get('unsetCookie','index/index/unsetCookie');

use think/Cookie

    public function setCookie(){
        Cookie::set('username','xiaoshang');
    }
    public function getCookie(Request $request){
        dump($request->cookie('username'));
    }
    public function unsetCookie(){
        Cookie::set('username',null);
    }

config中可以进一步设置Cookie和Session

httponly即只能服务器端只能通过http请求报文来获取客户端的cookie

0x02判断请求类型:

route.php

Route::any('index','index/index/index',['method'=>'get | post']);

表示只接收get或者post请求

index.php

 public function index(Request $request){
      if($request->isGet()){
          echo '当前是Get请求';
      }else if($request->isPost()){
          echo '当前是Post请求';
      }
  } 

0x03方法注册

首先在application/common.php中写一个方法:

function getUserInfo($request,$id){
    return 'this is from getUserInfo'.$id;
}

注意:该函数第一个参数的位置要留给request。

然后在application/index/controller/index.php中给Request类注册一个函数名为user,函数体为getUserInfo函数的函数体的方法:

 public function index(Request $request){
      Request::hook('user','getUserInfo');
      dump($request->user(333));
  } 

$request->user(333) 实际上调用的是common中getUserInfo方法,333将传给该方法的第二个参数

0x04Response

use think\Response;

Response::create方法可以控制响应的数据格式:xml,json,jsonp(和json差不多,但是jsonp可以跨域传输)等

这些格式,传入的data必须是关联数组。

class Index
{
  public function index(Request $request){

      return Response::create(['name'=>'刘德华','age'=>'33'],'xml');
  } 

}

create方法的源码:

public static function create($data = '', $type = '', $code = 200, array $header = [], $options = [])
    {
        $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type));
        if (class_exists($class)) {
            $response = new $class($data, $code, $header, $options);
        } else {
            $response = new static($data, $code, $header, $options);
        }

        return $response;
    }

助手函数:

json() 以json格式返回数据

xml() 以xml格式返回数据

jsonp() 以jsonp格式返回数据

  public function index(Request $request){
      $data = ['name'=>'liudehua','age'=>23];
      return json($data);
    //   return jsonp($dat);
    //   return xml($data);
  } 

以上这些助手函数都是对Response::create的封装,返回值都是一个对象。

helper.php中的源码


if (!function_exists('json')) {
    /**
     * 获取\think\response\Json对象实例
     * @param mixed   $data 返回的数据
     * @param integer $code 状态码
     * @param array   $header 头部
     * @param array   $options 参数
     * @return \think\response\Json
     */
    function json($data = [], $code = 200, $header = [], $options = [])
    {
        return Response::create($data, 'json', $code, $header, $options);
    }
}

redirect($url=[],) 重定向

if (!function_exists('redirect')) {
    /**
     * 获取\think\response\Redirect对象实例
     * @param mixed         $url 重定向地址 支持Url::build方法的地址
     * @param array|integer $params 额外参数
     * @param integer       $code 状态码
     * @param array         $with 隐式传参
     * @return \think\response\Redirect
     */
    function redirect($url = [], $params = [], $code = 302, $with = [])
    {
        if (is_integer($params)) {
            $code   = $params;
            $params = [];
        }
        return Response::create($url, 'redirect', $code)->params($params)->with($with);
    }
}

view()

发布了156 篇原创文章 · 获赞 19 · 访问量 8916

猜你喜欢

转载自blog.csdn.net/weixin_43415644/article/details/104312648