errorContainer是什么? 這個控制器用在哪兒合適?
errorContainer是個單例,所以,就等于是一個內存緩存。從index業務開始,不管中間是調用了logic的還是model的還是其他的controller的控制器,errorContainer中的數據都是同步一樣的。直到此用戶請求結束,進程結束。
errorContainer主要是為業務方法只返回true|false結果
當返回為true時代表執行正確。
當返回為false時,執行錯誤,在controller中想知道具體錯誤則調用 errorContainer->getLastCode() 或者getLastMsg() 或者 getAllError
-----------------
DEMO:
在controller中:
~~~
$errorObj = errorContainer::instance();
$auth = new userAuthentic($planId, $this->uid, $pic);
// 檢查 根據配置找到對應的方法 是否存在
if(!$auth->auth()){
failReturn($errorObj->getLastCode(), $errorObj->getLastMsg());
}
~~~
在userAuthentic中:
~~~
public function auth()
{
if(empty($this->info['realName'])){
errorContainer::instance()->setError('cajl003', '缺少真實姓名');
return false;
}
// 中間省略一些代碼
if($faceRet > 0.747){
return true;
}else{
errorContainer::instance()->setError('cajl005', '人臉對比失敗,分值過低');
return false;
}
}
~~~
-----------------
~~~
<?php
namespace youwen\exwechat;
/**
* 錯誤信息容器
*/
class errorContainer
{
/**
* @var object 對象實例
*/
protected static $instance;
// error[] = ['code'=>'xx', 'msg'='xx'];
protected static $allError=[];
protected static $lastErrorCode = 0;
protected static $lastErrorMsg = '';
/**
* 架構函數
* @access protected
* @param array $options 參數
*/
protected function __construct($options = [])
{
}
/**
* 初始化
* @access public
* @param array $options 參數
* @return \loan\app\logic\errorContainer
*/
public static function instance($options = [])
{
if (is_null(self::$instance)) {
self::$instance = new static($options);
}
return self::$instance;
}
/**
* 獲取最后一條錯誤碼
* @author baiyouwen
*/
public function getLastCode()
{
return self::$lastErrorCode;
}
/**
* 獲取最后一條錯誤信息
* @author baiyouwen
*/
public function getLastMsg()
{
return self::$lastErrorMsg;
}
/**
* 設置錯誤信息
* @author baiyouwen
*/
public function setError($code, $msg)
{
self::$lastErrorCode = $code;
self::$lastErrorMsg = $msg;
self::$allError[] = ['code'=>$code, 'msg' => $msg];
return true;
}
/**
* 獲取全部錯誤信息
* @author baiyouwen
*/
public function getAllError()
{
return self::$allError;
}
}
~~~