ThinkPHP6学习笔记2

发布时间 2023-08-19 18:27:45作者: ncsb

门面模式 facade

facade 不能在模型里面建立关联关系: 这里是属于注入是不能使用facade类的

Facade 怎么获取model实例对象

- facede instance方法

$model = TestFacadeModel::instance();



- 容器类直接实例化
$model = app(TestModel::class,[],true);


- facade定义类 新建实例化方法
public static function getNewInstance(...$args){
	return self::createFacade(\app\model\TestModel::class,$args,true);
}

依赖注入的的时候需要使用原生的类

依赖注入的优势是支持接口的注入,而Facade则无法完成。

tp6 Request类

  • app\Request 控制器自动注入Request对象,继承于 think\Request
$this->request->get('name'); // 获取get值
$this->request->post('name'); // 获取post值
$this->request->getContent();// 获取body内容

  • think\Request
    TP框架请求基类

  • think\facade\Request
    think\Request 类的门面模式

think\facade\Request::get('name');// 获取get参数

think\facade\Request::file('file');// 获取文件对象
  • Request() 返回的对象就是 app\Request

  • TP框架设置请求对象

 
    // 输入body内容获取
    public function __construct()
    {
        // 保存 php://input
        $this->input = file_get_contents('php://input');
    }

      // __make方法 请求对象设置
      $request->header = array_change_key_case($header);
      $request->server = $_SERVER;
      $request->env    = $app->env;

      $inputData = $request->getInputData($request->input);

      $request->get     = $_GET;
      $request->post    = $_POST ?: $inputData;
      $request->put     = $inputData;
      $request->request = $_REQUEST;
      $request->cookie  = $_COOKIE;
      $request->file    = $_FILES ?? [];
      
      //  

=========== 

  • 请求的json,为什么post可以直接获取到,看下面代码
  // 获取body原始内容 
   public function getContent(): string
    {
        if (is_null($this->content)) {
            $this->content = $this->input;
        }

        return $this->content;
    }

  $inputData = $request->getInputData($request->input);
   $request->post    = $_POST ?: $inputData;

   protected function getInputData($content): array
    {
        $contentType = $this->contentType();
        if ('application/x-www-form-urlencoded' == $contentType) {
            parse_str($content, $data);
            return $data;
        } elseif (false !== strpos($contentType, 'json')) {
            return (array) json_decode($content, true);  // 
        }

        return [];
    }

组装 mysql whereRaw


$whereRaw = '1=1';
if (!empty($params['testing_value'])) {
	$whereRaw = 'appreciation & ' . $params['testing_value'];
}
$query->whereRaw($whereRaw)

SELECT * FROM `oc_t_product_reserve` WHERE  `is_del` = 0  
AND ( appreciation & 512 ) ORDER BY `create_date` DESC LIMIT 0,10

appreciation & 512 > 0 才算满足确实算是可以的

mysql field排序函数

$res = PickTaskModel::with([])
   ->orderRaw('field(task_status,4,0,5,3),id asc')
	->select();