TP5.1的Request以及構造方法注入以及助手函數的使用


第一個是構造方法的使用

<?php

namespace app\index\controller;

use think\Request;

class Index 
{
    /**
     * @var \think\Request Request實例
     */
    protected $request;
    
    /**
     * 構造方法
     * @param Request $request Request對象
     * @access public
     */
    public function __construct(Request $request)
    {
		$this->request = $request;
    }
    
    public function index()
    {
		return $this->request->param('name');
    }    
}

 這樣子就可以在下面的方法中使用$this->request進行獲取;

為什么要用這種方法呢?當然並不是一定的,如果你要直接用的話你可以直接使用

return $this->request->param('name');

只要的你類繼承了系統的基類

但是還有一個就是比較不好的就是Request:: 的使用情況:

<?php

namespace app\index\controller;

use think\Controller;
use think\facade\Request;

class Index extends Controller
{
    
    public function index()
    {
		return Request::param('name');
    }    
}

首先他無法在__contruct的構造函數中進行獲取

其次他無法直接獲取出一個數組:情況是

只是用Request::param('arr')無法獲取到參數值(會報錯),但可以這么做,$params = Request::param();$arr = $params['arr'];這樣可以獲取到數組,但沒有Request::param('arr')來的直接方便,這應該是方法設計上的缺陷吧!

簡單來說如果你的構造函數內需要用到request信息的話就不能使用Request這個方式。

但是有一個小技巧可以繞過去,那就是tp5.1的前置操作

//前置操作
    protected $beforeActionList = [
        'inSet',      
    ];
    public function inSet()
    {   

          $id = Request::param('id');

    }

這樣子就可以進行類似構造函數的使用相對來說比較方便。但是看情況而用

構造函數在使用一次new的時候已經執行並且只執行一次

而前置函數你每次使用類方法的時候都會執行一次,所以說本地項目推薦使用構造

接口項目本人推薦使用前置方法!到此request相關介紹完畢,喜歡的可以點個關注吧!謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM