ThinkPHP入门-请求和响应

ThinkPHP入门-请求和响应

  1. 参考:ThinkPHP5快速入门-请求和响应
  2. 以下为个人看文档的总结,备不时之需,需要的请转1中的参考文献。
  3. 学习的时候以5.1版本作为学习的版本。
  4. 本节主要为请求和响应的部分。
  5. 侵删

一、请求对象

  1. Request请求对象的作用是与客户端进行交互,收集客户端的From、Cookies、超链接、或者收集服务器的环境变量。
  2. Request对象是从客户端像服务器发出请求,包括用户提交的信息,以及客户端的一些信息,客户端可以通过HTML表单活在网页地址后面提供参数的方法提交数据,然后通过Request对象的相关方法来获取这些数据。Request的各种方法用来处理客户端浏览器提交的请求中的各项参数和选项。
  3. Request对象的主要职责是统一和更安全的获取当前的请求信息,避免直接操作$_GET$_POST$_REQUEST$_SESSION$_COOKIE,甚至$_FILES等全局变量,而是统一使用Request对象提供的方法来获取请求变量。
1.1 传统方式调用
  1. 传统方式只是为了显示如何将Request实例化,开发中很少使用,参考教程中并没有成功。
1.2 继承think/Controller
  1. 该控制器集成了think/Controller,简化后如夏所示,可以访问

    <?php
    namespace app\index\controller;
    use think\Controller;
    class Index extends Controller
    {
        public function hello($name = 'World')
        {
            // 获取当前URL地址 不含域名
            echo 'url: ' . $this->request->url() . '<br/>';
            return 'Hello,' . $name . '!';
        }
    }
    
1.3 自动注入请求对象
  1. 如果没有继承think/Controller,则可以使用Request对象注入的方式来简化调用,系统建议使用,hello方法的request参数是系统自动注入的,不需要通过URL请求传入。

    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request, $name = 'World')
        {
            // 获取当前URL地址 不含域名
            echo 'url: ' . $request->url() . '<br/>';
            return 'Hello,' . $name . '!';
        }
    }
    
1.4 动态绑定属性
  1. 和model相关,暂时无法验证
1.5 使用助手函数
  1. 如果没有继承think/Controller,也不想给操作方法添加额外的Request对象参数,那么也可以使用系统提供的助手函数,通常情况下没有特别的说明,均采用自动注入请求的方式来使用。

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello($name = 'World')
        {
            // 获取当前URL地址 不含域名
            echo 'url: ' . request()->url() . '<br/>';
            return 'Hello,' . $name . '!';
        }
    }
    
  2. 在5.1中不需要使用Request::instance(),然后再调用方法直接使用Facade特性即可。

    <?php
    namespace app\index\controller;
    use think\facade\Request;
    class Index
    {
        public function hello($name = 'World')
        {
            // 获取当前URL地址 不含域名
            echo 'url: ' . Request::url() . '<br/>';
            return 'Hello,' . $name . '!';
        }
    }
    

二、请求信息

2.1. 获取请求变量
  1. 系统推荐使用param的方法来统一获取当前的请求变量,该方法最大的优势是让你不需要区分当前的请求类型而使用不同的全局变量或者方法,并且可以满足大部分的参数需求。

    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request)
        {
            echo '请求参数:';
            dump($request->param());
            echo 'name:'.$request->param('name');
        }
    }
    
  2. 可以通过访问的URL地址来显示结果
    http://localhost/index/index/hello.html?name=thinkphp2&test=add
    页面的输出结果为:

    请求参数:
    array(2) {
      ["name"] => string(9) "thinkphp2"
      ["test"] => string(3) "add"
    }
    name: thinkphp2
    
  3. 系统提供了一个input助手函数来简化了Request对象的param方法,
    param方法获取的参数会自动判断当前的请求,以POST请求为例的话,参数的优先级分别为:
    路由变量 > 当前请求变量($_POST变量) > $_GET变量
    这里的路由变量值的是路由规则俩面定义的变量或者PATH_INFO地址中的变量。路由变量无法使用get方法或者$_GET变量获取。

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello()
        {
            echo '请求参数:';
            dump(input());
            echo 'name:'.input('name');
        }
    }
    
  4. param方法支持变量的过滤和默认值,可以通过下面的URL访问
    http://localhost/index/index/hello.html?name=thinkphp5&test=add

    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request)
        {
            echo 'name:'.$request->param('name','World','strtolower');
            echo '<br/>test:'.$request->param('test','thinkphp','strtoupper');
        }
    }
    


    页面的输出结果为:

    name: thinkphp5
    test: ADD
    
  5. 也可以设置全局的过滤方法,设置默认全局的过滤规则,多个数组或者逗号分隔,具体配置在config/app.php下的'default_filter' => 'htmlspecialchars ',

  6. 除了param方法之外,``Request`对象可也以用于获取其他的输入参数

    扫描二维码关注公众号,回复: 5810525 查看本文章
    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request)
        {
            echo 'GET参数:';
            dump($request->get());
            echo 'GET参数:name';
            dump($request->get('name'));
            echo 'POST参数:name';
            dump($request->post('name'));
            echo 'cookie参数:name';
            dump($request->cookie('name'));
            echo '上传文件信息:image';
            dump($request->file('image'));
        }
    }
    

    页面的输出结果为

    GET参数:
    array (size=1)
      'name' => string 'thinkphp' (length=8)
    GET参数:name
    string 'thinkphp' (length=8)
    POST参数:name
    null
    当前请求(自动识别请求类型)的参数:name
    string 'thinkphp' (length=8)
    cookie参数:name
    null
    上传文件信息:image
    null
    

    使用助手函数的代码,感觉还是使用助手函数比较简单,下面的助手函数的参数中有一个注意,第一个'get.'中有一个点,这个点表示获取所有的get过来的参数的数组的值,若参数为'get',则会显示NULL,dump函数带回车

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello()
        {
            echo 'GET参数:';
            dump(input('get.'));
            echo 'GET参数:name';
            dump(input('get.name'));
            echo 'POST参数:name';
            dump(input('post.name'));
            echo 'cookie参数:name';
            dump(input('cookie.name'));
            echo '上传文件信息:image';
            dump(input('file.image'));
        }
    }
    
  7. 获取变量的方法如下,其中除了file方法之外,其他的方法都支持默认值和过滤的方法:

方法 作用
param 获取请求变量
get 获取$_GET变量
post 获取$_POST变量
put 获取PUT请求变量
delete 获取DELETE请求变量
patch 获取PATCH请求变量
request 获取$_REQUEST变量
route 获取路由(URL)变量
session 获取$_SESSION变量
cookie 获取$_COOKIE变量
server 获取$_SERVER变量
env 获取$_ENV变量
file 获取上传文件信息
2.2 获取请求参数
  1. 获取请求的参数的实例,通过URL访问
    http://localhost/index/index/hello.html?name=thinkphp5&test=add

    <?php
    namespace app\index\controller;
    
    use think\Request;
    
    class Index
    {
        public function hello(Request $request)
        {
            echo '请求方法:' . $request->method() . '<br/>';
            echo '资源类型:' . $request->type() . '<br/>';
            echo '访问IP:' . $request->ip() . '<br/>';
            echo '是否AJax请求:' . var_export($request->isAjax(), true) . '<br/>';
            echo '请求参数:';
            dump($request->param());		// 这个必须使用dump打印
            echo '请求参数:仅包含name';
            dump($request->only(['name']));
            echo '请求参数:排除name';
            dump($request->except(['name']));
        }
    }
    

    结果为

    请求方法: GET
    资源类型: xml
    访问IP: ::1
    是否为AJax请求: false
    请求参数:
    array(2) {
      ["name"] => string(9) "thinkphp5"
      ["test"] => string(3) "add"
    }
    请求参数: 仅包含name
    array(1) {
      ["name"] => string(9) "thinkphp5"
    }
    请求参数: 排除name
    array(1) {
      ["test"] => string(3) "add"
    }
    
2.3 获取URL信息
  1. 获取URL信息的实例,请求的URL地址为
    http://localhost/index/index/hello.html?name=thinkphp5&test=add

    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request,$name = 'World')
        {
            // 获取当前域名
            echo 'domain: ' . $request->domain() . '<br/>';
            // 获取当前入口文件
            echo 'file: ' . $request->baseFile() . '<br/>';
            // 获取当前URL地址 不含域名
            echo 'url: ' . $request->url() . '<br/>';
            // 获取包含域名的完整URL地址
            echo 'url with domain: ' . $request->url(true) . '<br/>';
            // 获取当前URL地址 不含QUERY_STRING
            echo 'url without query: ' . $request->baseUrl() . '<br/>';
            // 获取URL访问的ROOT地址
            echo 'root:' . $request->root() . '<br/>';
            // 获取URL访问的ROOT地址
            echo 'root with domain: ' . $request->root(true) . '<br/>';
            // 获取URL地址中的PATH_INFO信息
            echo 'pathinfo: ' . $request->pathinfo() . '<br/>';
            // 获取URL地址中的PATH_INFO信息 不含后缀
            echo 'pathinfo: ' . $request->path() . '<br/>';
            // 获取URL地址中的后缀信息
            echo 'ext: ' . $request->ext() . '<br/>';
    
            return 'Hello,' . $name . '!';
        }
    }
    

    结果为:

    domain: http://localhost
    file: /index.php
    url: /index/index/hello.html?name=thinkphp5&test=add
    url with domain: http://localhost/index/index/hello.html?name=thinkphp5&test=add
    url without query: /index/index/hello.html
    root: 
    root with domain: http://localhost
    pathinfo: index/index/hello.html
    pathinfo: index/index/hello
    ext: html
    Hello, thinkphp5!
    
  2. URL请求和信息方法总结如下,url、baseUrl、baseFile、root方法如果传入true,表示获取包含域名的地址。

方法 作用
domain 获取当前的域名
url 获取当前的完整URL地址
baseUrl 获取当前的URL地址,不含QUERY_STRING
baseFile 获取当前的SCRIPT_NAME
root 获取当前URL的root地址
pathinfo 获取当前URL的pathinfo地址
path 获取当前URL的pathinfo地址,不含后缀
ext 获取当前URL的后缀
type 获取当前请求的资源类型
scheme 获取当前请求的scheme
query 获取当前URL地址的QUERY_STRING
host 获取当前URL的host地址
port 获取当前URL的port号
protocol 获取当前请求的SERVER_PROTOCOL
remotePort 获取当前请求的REMOTE_PORT
2.4 获取当前模块/控制器/操作信息
  1. 操作方法的实例如下,输入的URL地址如下,其中controller的方法获取的是驼峰命名的世纪的控制器命名,其他的都是小写返回,经过测试,这个控制器显示的是class后面跟着的名称,不是php文件的名称
    http://localhost/index/index/hello.html?name=thinkphp5&test=add

    public function hello(Request $request, $name = 'World')
    {
        echo '模块:'.$request->module();
        echo '<br/>控制器:'.$request->controller();
        echo '<br/>操作方法:'.$request->action();
    }
    

    结果显示为:
    模块: index
    操作器: Index
    操作方法: hello

2.5 获取路由和调度信息
  1. 操作方法的实例如下,输入的URL地址如下
    http://localhost/hello/thinkphp

    <?php
    namespace app\index\controller;
    use think\Request;
    class Index
    {
        public function hello(Request $request, $name = 'World')
        {
            echo '路由信息:';
            dump($request->routeInfo());
            echo '调度信息:';
            dump($request->dispatch());
            return 'Hello,' . $name . '!';
        }
    }
    

    页面输出的信息为

    路由信息:
    array(4) {
      ["rule"] => string(13) "hello/<name?>"
      ["route"] => string(17) "index/index/hello"
      ["option"] => array(1) {
        ["merge_rule_regex"] => bool(false)
      }
      ["var"] => array(1) {
        ["name"] => string(8) "thinkphp"
      }
    }
    调度信息:
    object(think\route\dispatch\Module)#15 (6) {
      ["controller"] => string(5) "index"
      ["actionName"] => string(5) "hello"
      ["dispatch"] => array(3) {
        [0] => string(5) "index"
        [1] => string(5) "index"
        [2] => string(5) "hello"
      }
      ["param"] => array(1) {
        ["convert"] => bool(false)
      }
      ["code"] => NULL
      ["convert"] => bool(false)
    }
    Hello, thinkphp!
    

三、 响应对象

  1. Response对象用于动态响应客户端请示、控制发送给用户的信息,并将动态生成响应,通常用于输出给客户端或者浏览器,其中ThinkPHP5Response响应对象由think\Response类或者子类完成。
    我的理解这个应该就是服务端响应给移动端或者前段访问的数据吧。
3.1 自动输出
  1. 大多数情况下,不需要关注Response的对象本身,只是需要在控制器的操作方法中返回数据即可,系统会根据配置文件中的参数来确定你返回的数据的响应输出的类型。
    1)在配置default_return_type(默认是html)和default_ajax_return(可以选择json、xml)中配置类型。
    2)默认的自动响应输出是会自动判断是否为AJAX请求,如果是的话会自动输出default_ajax_return配置的输出类型。

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello()
        {
            $data = ['name' => 'thinkphp', 'status' => '1'];
            return $data;
        }
    }
    

    在使用这个之后,直接访问http://localhost/hello会产生错误,显示variable type error: array,需要做的事,将default_return_type的参数由html改写为jsonxml,这样输出的结果就没有错误了。

3.2 手动输出
  1. 上面的情况是直接输出的$data,是由系统的配置文件控制的输出类型,也可以在return的地方直接决定返回值的类型格式为哪种,支持json和xml。

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello()
        {
            $data = ['name' => 'thinkphp', 'status' => '1'];
            return json($data);
            // return xml($data, 201);
        }
    }
    
  2. 还可以在返回中控制http的状态码,正常返回的是200,表示成功,还可以返回其他的状态码,可以使用其他的状态码,也可以发送更多的响应头的信息

    <?php
    namespace app\index\controller;
    class Index
    {
        public function hello()
        {
            $data = ['name' => 'thinkphp', 'status' => '1'];
            return json($data, 201);
            // return json($data, 201, ['Cache-control' => 'no-cache,must-revalidate']);
            // return json($data)->code(201)->header(['Cache-control' => 'no-cache,must-revalidate']);
        }
    }
    

    默认支持的输出类型包括

    类型 快捷方法
    模板输出 view
    ON输出 json
    ONP输出 jsonp
    L输出 xml
    重定向 redirect
3.3 页面跳转
  1. 如果进行一些简单的页面操作提示或者是重定向,可以引入traits\controller\Jump,这样就可以使用相关的页面跳转和重定向的方法,下面的实例是在页面传入name参数为thinkphp的时候,跳转到欢迎界面,其他情况则跳转到guest界面。

    <?php
    namespace app\index\controller;
    class Index
    {
        use \traits\controller\Jump;
        public function index($name='')
        {
            if ('thinkphp' == $name) {
                $this->success('欢迎使用ThinkPHP
            5.0','hello');
            } else {
                $this->error('错误的name','guest');
            }
        }
        public function hello()
        {
            return 'Hello,ThinkPHP!';
        }
        public function guest()
        {
            return 'Hello,Guest!';
        }
    }
    
  2. 上面使用的是use \traits\controller\Jump;,引用了一个Jumptrait,这个是PHP5.4版本的新特性,如果你的控制器类是继承\think\Controller的话,系统就已经自动引入了\traits\controller\Jump,不用再二次引入。
    1)所以在访问localhost的时候,浏览器会显示错误的name,然后过3秒跳转到http://localhost/index/index/guest.html
    2)在访问localhost?name=thinkphp的时候,浏览器会显示欢迎使用ThinkPHP5.0,然后跳转到http://localhost/index/index/hello.html

3.4 页面重定向
  1. 如果要进行页面重定向跳转,可以使用redirect方法,该方法默认的是302条转,如果不需要刻意使用第二个参数进行301跳转,也可以使用助手函数直接redirect函数进行重定向。

    <?php
    namespace app\index\controller;
    class Index
    {
        use \traits\controller\Jump;
        public function index($name='')
        {
            if ('thinkphp' == $name) {
                $this->redirect('http://thinkphp.cn');
                // $this->redirect('http://thinkphp.cn',301);
                // return redirect('http://thinkphp.cn');
            } else {
                $this->success('欢迎使用ThinkPHP','hello');
                // return 'Hello,ThinkPHP!';
            }
        }
        public function hello()
        {
            return 'Hello,ThinkPHP!';
        }
    }
    

猜你喜欢

转载自blog.csdn.net/Ankie_/article/details/87167291