<?php
namespace appapicontroller;
use thinkController;
use thinkRequest;
use appapicontrollerSend;
use appapicontrollerOauth;
class Api
{
use Send;
public function init()
{
//所有ajax请求的options预请求都会直接返回200,如果需要单独针对某个类中的方法,可以在路由规则中进行配置
if($this->request->isOptions()){
return self::returnMsg(200,'success');
}
//配置不要鉴权的方法白名单
if(!in_array($this->request->controller().'/'.$this->request->action().'/'.strtolower($this->request->method()),config('allow_method'))){
//授权处理
$oauth = app('appapicontrollerOauth'); //tp5.1容器,直接绑定类到容器进行实例化
return $this->clientInfo = $oauth->authenticate();;
}
}
}
其中return self::returnMsg();这个方法是这个类文件里面没有的,也没有继承相关的类,甚至不是系统的方法,那么从何而来呢?主要就是我们use了Send的命名空间,然后在类方法当中进行use,然后我们就可以使用这样的类库的类了。
但是对于这种类库被类中直接use的类声明有所特殊;
具体如下
<?php
namespace appapicontroller;
use thinkController;
use thinkRequest;
trait Send
{
/**
* 返回成功
*/
public static function returnMsg($code = 200,$message = '',$data = [],$header = [])
{
http_response_code($code); //设置返回头部
$return['code'] = (int)$code;
$return['message'] = $message;
$return['data'] = is_array($data) ? $data : ['info'=>$data];
// 发送头部信息
foreach ($header as $name => $val) {
if (is_null($val)) {
header($name);
} else {
header($name . ':' . $val);
}
}
exit(json_encode($return,JSON_UNESCAPED_UNICODE));
}
}
可以看到通过的是trait的类声明,主要是
根命名空间是一个关键的概念,以上面的 hinkcachedriverFile
类为例,think
就是一个根命名空间,其对应的初始命名空间目录就是系统的类库目录(thinkphp/library/think
),我们可以简单的理解一个根命名空间对应了一个类库包。