Skip to content

kouGrace 基础控制器

基础控制器

class kouGrace{...} 说明
所有的自定义控制器必须继承 kouGrace 基础控制器,基础控制器内置了一些常用的方法以便您的开发!您也可以扩展 kouGrace 来实现更为便捷的开发。

源码解析

php
class kouGrace{
    public    $gets;                // get参数
    public    $templateDir;         // 视图层存放目录
    public    $tableName  = null;   // 核心数据表名
    public    $tableKey   = null;   // 数据表主键
    public    $db;                  // 数据表操作对象
    public    $order      = null;   // 数据排序规则
    public    $postFilter = true;   // 是否过滤 $_POST 数据内的 < > , 可防止跨站攻击
    public    $pageInfo   = array('', '', ''); // 网页信息 array(页面标题, 页面关键字, 页面描述)
    public    $header = [];            // 网站属性 type:array [ title:网站标题 ,description:网站描述,keywords:网站关键字 或者其他的]
    protected $cacher     = null;    // 缓存对象
    protected $cacheName;    // 缓存名称
    public function __construct(){
        // 保存 php://input
        $this->input = file_get_contents('php://input');
    }

    // 初始化函数
    public function __init(){
        // 当前视图层目录
        $this->templateDir =  KG_PATH.'/'.KG_MODULE.'/'.KG_VIEW_DIR_NAME.'/';
        // 如果控制器内有设置表名字段,则自动连接数据库
        if($this->tableName != null){$this->db = db($this->tableName);}
        // 过滤 $_POST
        if(!empty($_POST)){
            // 局部过滤,避免跨站攻击 默认开启 true , 手动关闭 可以设置此参数为 false
            if($this->postFilter){$_POST = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;', ''), $_POST);}
        }
        // 开启全局过滤    
        if (KG_POST_FILTER ==  true){
            $_POST = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;', ''), $_POST);
        }
        // 过滤 $_GET
        if(!empty($_GET)){$_GET = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_GET);}
        if(!empty($this->gets)){$this->gets = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $this->gets);}
    }

    public function index(){}

    /**
     * 加载视图展示
     * @param $tplName string 视图文件名
     */
    public function display($tplName = null){
        if(KG_VIEW_TYPE == 'file'){
            // 默认 file类型的视图文件路径 模块/视图层/控制器_方法名.php
            $tplUrl = is_null($tplName) ?  $this->templateDir.KG_C.'_'.KG_M.'.php' : $this->templateDir.$tplName;
        }else{
            // dir 类型的视图文件路径 模块/视图层/控制器/方法名.php
            $tplUrl = is_null($tplName) ?  $this->templateDir.KG_C.'/'.KG_M.'.php' : $this->templateDir.$tplName;
        }
        if(is_file($tplUrl)){include($tplUrl);}
    }

    /**
     * 输出 json 形式的信息并终止程序运行
     * @param $data 输出信息
     * @param $status 状态信息
     */
    protected function json($data, $status = 'ok'){
        kgExit(json_encode(array('status' => $status, 'data' => $data),JSON_UNESCAPED_UNICODE));
    }
    // 获取数据列表
    protected function dataList($everyPagerNum = 20, $fields = '*'){
        if($this->order == null){$this->order = $this->tableKey.' desc';}
        $arr = $this->db->page($everyPagerNum)->order($this->order)->fetchAll($fields);
        $this->pager = $arr[1];
        return $arr[0];
    }
    // 利用 id 获取一条数据
    protected function getDataById(){
        if(empty($this->gets[0])){return null;}
        return $this->db->where($this->tableKey .' = ?', array(intval($this->gets[0])))->fetch();
    }
    // 获取一条数据并以默认值形式复制给对应表单元素
    protected function getDefaultVal($exception = array()){
        if(empty($this->gets[0])){return null;}
        $data = $this->db->where($this->tableKey .' = ?', array(intval($this->gets[0])))->fetch();
        $jsonPreData = array();
        if(!empty($exception) && !is_array($exception)){$exception = explode(',', $exception);}
        foreach($data as $k => $v){
            if(!in_array($k, $exception)){
                $jsonPreData[$k] = $data[$k];
            }
        }
        echo '<script>$(function(){';
        echo 'var dataobject = '.json_encode($jsonPreData).';';
        if($data){
            foreach($data as $k => $v){if(!in_array($k, $exception)){echo '$("input[name='.$k.']").val(dataobject.'.$k.');';}}
        }
        echo '});</script>';
        return $data;
    }
    // 跳转到应用首页
    public function skipToIndex(){header('location:'.KG_SROOT); exit;}

    // 语言包设置 *
    protected function setLang($langType){
        pgSetCookie('GraceLang', $langType);
    }

    // 初始化 gets 数据
    // 如果某个指定的数据为空则进行定义及赋值
    protected function initVal($key, $val = ''){
        if(empty($this->gets[$key])){$this->gets[$key] = $val;}
    }
    // 将 gets 指定数据整数化
    protected function intVal($key, $val = 0){
        if(empty($this->gets[$key])){
            $this->gets[$key] = 0;
        }else{
            $this->gets[$key] = intval($this->gets[$key]);
        }
    }
    // 获取缓存对象
    protected function getCacher(){
        if(!empty($this->cacher)){return null;}
        $config         = sc('cache');
        if(empty($config)){throw new graceException('缓存设置错误',100009);}
        if(!in_array($config['type'], sc('allowCacheType'))){throw new graceException('缓存类型错误',100010);}
        $type           = strtolower($config['type']);
        $className      = 'kouGrace\\tools\\caches\\'.$type.'Cacher';
        $this->cacher   = $className::getInstance($config);
    }

    // 进行缓存工作
    protected function cache($name, $queryMethod, $id = null, $timer = 3600, $isSuper = true){
        if(KG_CLOSE_CACHE){
            $queryRes    = $this->$queryMethod();
            $this->$name = $queryRes;
            return false;
        }
        $this->getCacher();
        $this->cacheName = graceCacheName($name, $id, $isSuper);
        $cachedRes = $this->cacher->get($this->cacheName);
        if($cachedRes){$this->$name = $cachedRes; return true;}
        $queryRes = $this->$queryMethod();
        $this->cacher->set($this->cacheName, $queryRes, $timer);
        $this->$name = $queryRes;
    }

    // 清除全部缓存
    public function clearCache(){
        $this->getCacher();
        $this->cacher->clearCache();
    }

    // 清除指定缓存
    public function removeCache($name, $id = null, $isSuper = true){
        $this->getCacher();
        $name = graceCacheName($name, $id, $isSuper);
        $this->cacher->removeCache($name);
    }
}

基础控制器扩展

您可以扩展基础控制器,然后自己创建的控制器都继承自己的控制器,这样可以实现更多全局功能,例 :
网站后台控制器扩展 :

php
<?php
/**
 * 管理后台 -> 基础控制器
 */
class baseController extends kouGrace{
   
   public function __init(){
      parent::__init();
      $this->checkLogin();
   }
   
   protected function checkLogin($auth = null){
       if(empty($_SESSION['graceMangerId'])){
           // 注意 login 控制器不要继承 baseController 而是 grace
           // 要不会造成死循环
           header('location:'.PG_SROOT.'login'); 
           pgExit();
       }
    }
    //... 其他代码

上面的代码演示了 :
网站后台管理系统开发时,大部分页面都需要检查后台管理员的登录信息,我们在自定义基础控制器内封装 checkLogin() 方法对用户登录信息进行检查,如果用户没有登录会跳转到登陆页面。同时利用 __init() 函数自动执行检查函数。
有了上面的基础控制器,我们在开发网站后台时就可以这样创建控制器 :
class 自定义控制 extends 自定义基础控制器。

php
<?php
class systemController extends baseController{
   
   public function __init(){
      parent::__init();
      $this->checkAuth();
   }
   
   public function index(){}
   //....
}

Released under the MIT License.