thinkphp5 underlying base type of packaging, the internal class function

Thinkphp5 recorded custom underlying base class, class function using internal notes from the note most tp manual.

 

 

Encapsulating the underlying common code

In the controller base class plays a vital role in the security code for the entire project, complexity, legibility must look at the base class architecture of your project.

For example, in the api function requires a certain function, we can write in the base class.

Examples of a base paste class returns an error code:

<?php

namespace app\member\controller; class Base extends \app\base\controller\Base { static public function showReturnCode($code = '', $data = [], $msg = '') { $return_data = [ 'code' => '500', 'msg' => '未定义消息', 'data' => $code == 1001 ? $data : [], ]; if (empty($code)) return $return_data; $return_data['code'] = $code; if(!empty($msg)){ $return_data['msg'] = $msg; }else if (isset(ReturnCode::$return_code[$code]) ) { $return_data['msg'] = ReturnCode::$return_code[$code]; } return $return_data; } static public function showReturnCodeWithOutData($code = '', $msg = '') { return self::showReturnCode($code,[],$msg); } }

Base class:

<? PHP 
namespace App \ Base \ the Controller; 

class ReturnCode 
{ 
    static  public  $ return_code = [
         '1001' => 'successful operation', 
        '1002' => 'You want to do it', // illegal way of non-ajax requests 
        '1003' => 'request parameter error', // as parameters incomplete, incorrect type 
        '1004' => 'please log in again to access', // not logged in or unauthorized 
        ' 1005 '=>' request authorization does not match ' // // Check unauthorized illegal request 
        ' 1006 '=>' fails to load data ' //
         ' 1010 '=>' data does not exist, ' //
         ' 1020 '=>'Enter the code is incorrect, ' //
         ' 1021 '=>' user ID or password is incorrect ", //
        '1022' => 'user account is disabled,' //
         '1030' => 'data operation failed', //
     ]; 
}

 

Then you can call

    Private  function getuid () {
         // database field into the page field 
        $ param = [
             'the userid' => 'the userid', 
            'UserPwd' => 'UserPwd', 
            'Mobile' => 'Mobile', 
        ]; 
        $ param_data = $ the this -> buildParam ( $ param );
         IF ( empty ( $ param_data [ 'the userid']) && empty ( $ param_data [ 'Mobile'])) return Self :: showReturnCodeWithOutData (1003 );
         $ check_login = $ the this ->doModelAction($param_data, 'base/Member.login', 'base/Member', 'checkLogin');
        if (!isset($check_login['code'])) $this->showReturnCodeWithSaveLog(1111);
        if ($check_login['code'] == 1001) {


        }
        return $check_login;

    }

 

 

A frame constructor

A constructor method to perform the initialization class, constructor, do not use the return keyword .

Well, we have what is doing in the constructor inside it?

  • Injection initialization data object, etc.
  • Pre-treatment work
  • Permission judgment

We look at the constructor TP5 controllers at initialization time he injected the request object , we inherited the controller can directly use $ this-> request to call, but also encapsulates the View class, while on the front of the property beforeActionList the method for processing.

public function __construct(Request $request = null)
    {
        if (is_null($request)) {
            $request = Request::instance();
        }
        $this->view    = View::instance(Config::get('template'), Config::get('view_replace_str'));
        $this->request = $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                $this->beforeAction($options) :
                $this->beforeAction($method, $options);
            }
        }
    }

 

For example, permission determination:

public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $user_agent = $this->request->server('HTTP_USER_AGENT');
        if (! strpos($user_agent, 'MicroMessenger') === false ) $this->isWechatBrowser = true;
        //判断提交方式和是否微信浏览器
        if ($this->request->method() == 'GET' && $this->=== isWechatBrowser not logged log in again//) {
            to true
            if (!$this->checkAuth()&& !$this->no_login )  $this->wxoauth();
            $this->isLogin=true;
            //设置全局登录
            $this->loginGlobal();
            if(!$this->isReg){
                if(!$this->checkUuidMobile()) $this->redirect('user/user_blind.html');
            }
        }

    }

 

Control up Inheritance:

? < PHP
 
namespace App \ API \ Controller; 


class WxpayAction the extends the Auth 
{ 
    public  function _initialize () 
    { 
        config ( 'default_return_type', 'HTML' ); 
        parent :: _ the initialize (); // the TODO: Change The AutoGenerated Stub 
    } 

    public  function index ( $ order_no = '2017020453102495' ) { 

        iF (! $ the this -> isWechatBrowser) {
          // ******* 
         for convenience omitted here demonstrate whether a payment verification order 
         
         further micro-channel payment payment itself replicated here He did not join the optimistic locking filter
         //*******
        $data=controller('base/WxPay')->payByOrderNo($order_no);
        $assign_data=[
            'title'=>'为了家健康--订单支付',
            'amount'=>$data['amount'],
            'order_no'=>$order_no,
            "jsApiParameters" =>$data['jsApiParameters'],
            'openid'=>$this->open_id,
            'data_md5'=>md5($order_no.$this->open_id.$data['amount']),$ the this
        ];MD5 verification (order number openid amount)//


        -> ASSIGN ( $ assign_data );
         return  $ the this -> FETCH ( 'wxpay / index' ); 

    } 


    public  function showOrdersPayOk ( $ order_no , $ ORDER_AMOUNT , $ data_md5 ) {
         // MD5 authentication (Order No. Amount openid) 
        IF ( MD5 ( $ order_no . $ the this -.> open_id $ ORDER_AMOUNT ) <> $ data_md5 ) {
             $ assign_data = [
                 'title' => 'to home health - paid wrong', 
                'Content' => 'you have to pay for orders Please check the number does not exist and then pay '! 
            ];
            the this $ -> ASSIGN ( $ assign_data );
             return  $ the this -> FETCH ( 'wxpay / ERR' ); 
        } the else { 

            $ assign_data = [
                 'title' => 'To Home Health - the payment order has been successful', 
                ' AMOUNT '=> $ ORDER_AMOUNT , 
                ' order_no '=> $ order_no , 
            ]; 
            $ the this -> ASSIGN ( $ assign_data );
             return  $ the this -> FETCH (' wxpay / OK ' );
        }
    }

    public function jsSign($url=''){
        $url= $url ? : $this->request->server('HTTP_REFERER');
        return json(controller('base/WxApi')->getJsSign($url));
    }

 

 

Frame using destructor

Destructor is a method of ending,

Example: Creating a virtual base class

? < PHP 
namespace App \ Base \ the Controller; 

use of Think \ Cache;
 use of Think \ the Controller;
 use of Think \ the Session;
 use of Think \ Loader;
 
abstract  class Base the extends the Controller 
{ 
    protected  $ error ;              // error when recording 
    protected  $ log = [];             // to save the recording 
    protected  $ savelog = to false ; 
    
    
    static  public  function showReturnCode ( $ code = '', $ Data = [], $ MSG = '')
    {
        $return_data = [
            'code' => '500',
            'msg' => '未定义消息',
            'data' => $code == 1001 ? $data : [],
        ];
        if (empty($code)) return $return_data;
        $return_data['code'] = $code;
        if(!empty($msg)){
            $return_data['msg'] = $msg;
        }else if (isset(ReturnCode::$return_code[$code]) ) {
            $return_data['msg'] = ReturnCode::$return_code[$code];
        }
        return $return_data;
    }
    
        protected function addLog($code='',$msg=''){
        $this->log[] =[
            'uuid' => $this->uuid,
            'url' => $this->request->url(true),
            'method' => $this->request->method(),
            'data' => $this->getData(),
            'ip' => $this->request->ip(),
            'code'=>$code,
            'desc' => $msg,
        ];
    }
    protected function toSaveLog(){
        $this->saveLog = true ;
        $this->addLog();
    }

    protected function showReturnCodeWithSaveLog($code = '', $data = [], $msg = ''){
        $this->= savelog to true ;
        $this->addLog($code,$msg);
        return self::showReturnCode($code, $data, $msg);
    }
    
    protected function getData(){
        if ($this->request->isPost()){
            return $this->request->post();
        }else{
            return $this->request->get();
        }
    }
    protected function saveLogAction(){
        if (!empty($this->log)){
            foreach($this->log as $value){
                dump($value);
            }
        }
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        //记录日志
        if (!empty($this->log) && $this->saveLog == true){
            $this->saveLogAction();
        }
    }
}

 

Controller Inheritance:

<?php

namespace app\member\controller;
use app\base\model\Member;
use think\Cache;
use think\Db;

class Test extends Base
{

    public function index(){

       return $this->showReturnCodeWithSaveLog(1001,'演示析构函数成功了');

    }



}

 

Guess you like

Origin www.cnblogs.com/-qing-/p/11334574.html