• tp5.1最新的类库使用规则


    <?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),我们可以简单的理解一个根命名空间对应了一个类库包。

  • 相关阅读:
    libyuv 代码结构分析,借用其NEON/ARM64优化代码
    Android 交叉编译 IPerf3
    Android Change TCP Congestion Control
    Unpack & Repack Android system.img & data.img
    Android can only be built by versions 3.81 and 3.82
    Build Android Kernel && Kernel Module
    换行符
    python之%s、%d、%f的使用
    Python+selenium 实现不定位元素,输入enter键
    进程间通信 (IPC) 方法总结(三)
  • 原文地址:https://www.cnblogs.com/hoewang/p/10257201.html
Copyright © 2020-2023  润新知