1. 程式人生 > >ci框架根據配置自動生成controller控制器和model控制器(改版本)

ci框架根據配置自動生成controller控制器和model控制器(改版本)

CI修改如下:

    if($modle_file=config_item('modle_file'))
    {
        if ($modle_file === TRUE)
        {
            $modle_file=config_item('modle_type');

            $MOF=& load_class('Newfile','core');

            //$MOF->createModule($modle_file);  //建立檔案載入類
            $MOF->createModule();
        }
    }


<?php

/**
 * 這是一個擴充套件類
 * 
 * 主要用來新增 常用的model模組還有controller控制器
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * model、controller擴充套件類
 *
 * @package    CodeIgniter
 * @subpackage Libraries
 * @category   Logging
 * @author     shaonian
 * @link        
 */
class CI_Newfile
{

    /**
     * 常用模組列表
     *
     * @var array
     */
    protected $_model_arr=['Admin'];
    
    //模組前戳
    protected $_model_prefix='Model_';

    //自定義模組
    protected $custom_model=[];

    /**
     * 常用控制器列表
     *
     * @var int
     */
    protected $_controller_arr = [];
    
    //自定義控制器
    protected $custom_controller=[];

    /**
     * 目錄許可權
     *
     * @var int
     */
    protected $_chmod = 0775;

    /**
     * 建立時間
     *
     * @var string
     */
    protected $_date_fmt = 'Y-m-d H:i:s';
    

    //獲取全部的定義
    protected $_arr_info=[];

    

    /**
     * 控制類
     *  
     * 其實這個類 也可以寫在擴充套件裡面 因為 ci本來就讓擴充套件用法的
     *
     * 這裡支援兩種方法 一種 在定義的環境下config配置 一種定義下的直接讀取單獨個配置檔案
     *
     * @return void
     */
    public function __construct($is_build=false)
    {
        $config =& get_config();  //載入全域性配置檔案

        if (!empty($config['custom_controller']))
        {
            $this->custom_controller=$config['custom_controller'];
        }

        if (!empty($config['custom_model']))
        {
            $this->custom_model=$config['custom_model'];
        }
    }

    

    /**
     * 根據路徑建立模組
     *
     * @param  [type] $path
     * @return void
     */
    public function createModule($is_type_system='new')
    {
            
        //根檔案
        // $Model_path_base=BASEPATH.'core/newfile/model/'.$is_type_system.DIRECTORY_SEPARATOR;

        // $this->mkdirs($Model_path_base); //遞迴建立目錄

        // $get_content=$this->file_get_contents_write($Model_path_base);


        //馬上

        //還有一種方法
        /**
         * $content=$get_content instanceof Iterator; 這個詳細的方法 看php手冊的 迭代介面
         */

        // foreach($get_content as $model_key=>$content)
        // {

        //     //建立檔案
        //     $this->mkdirs(APPPATH.'models/sys/');

        //     file_put_contents(APPPATH.'models/sys/'.$model_key.'.php', $content);
        // }


        if(!empty($this->custom_model)) {

            //迴圈自定義的控制器
            foreach($this->custom_model as $model_k=>$model_v) {
                    
                if (strpos($model_v, '/')!==false) {
                        
                    //這段程式處理前面的目錄的 支援無限極目錄
                    $dir_arr=explode('/', rtrim($model_v, '/'));
                    array_pop($dir_arr);
                    $dir_str=(count($dir_arr)>=2)?implode('/', $dir_arr):$dir_str[0];
                    $this->mkdirs(APPPATH.'models/'.$dir_str.DIRECTORY_SEPARATOR);

                } 
                //讀模板內容
                $content_con=$this->modelTpl($this->_model_prefix.ucwords($model_v));

                if(!empty($dir_str)) {

                    $file_path=APPPATH.'models/'.$dir_str.DIRECTORY_SEPARATOR.$this->_model_prefix.ucwords($model_v).'.php';
                    
                }
                $file_path=APPPATH.'models/'.$this->_model_prefix.ucwords($model_v).'.php';

                if (file_exists($file_path)==true) {
                    
                    continue;
                }

                //echo $file_path;
                file_put_contents($file_path, $content_con);

            }
        }
        
    }


    
    /**
     * 這裡用的是思想模板替換
     * 這裡我都沒判斷應用目錄是否可寫 這是不對的
     *
     * @param  string $is_type_system
     * @return void
     */
    public function createController($is_type_system='new')
    {
        //   //根檔案
        //   $controller_path_base=BASEPATH.'core/newfile/controller/'.$is_type_system.DIRECTORY_SEPARATOR;

        //   $this->mkdirs($controller_path_base); //遞迴建立目錄
  
        //   $get_content=$this->file_get_contents_write($controller_path_base);

        //   //這裡建立常用的程式碼
        // foreach($get_content as $controller_key=>$content)
        //   {
            
        //     //建立檔案
        //     $this->mkdirs(APPPATH.'controller/sys/');
  
        //     file_put_contents(APPPATH.'controller/sys/'.$controller_key.'.php', $content);
        // }

          //這裡建立配置檔案中的控制器,支援層級建立目錄

        if(!empty($this->custom_controller)) {

            //迴圈自定義的控制器
            foreach($this->custom_controller as $controller_k=>$controller_v) {
                    
                if (strpos($controller_v, '/')!==false) {
                        
                    //這段程式處理前面的目錄的 支援無限極目錄
                    $dir_arr=explode('/', rtrim($controller_v, '/'));
                    array_pop($dir_arr);
                    $dir_str=(count($dir_arr)>=2)?implode('/', $dir_arr):$dir_str[0];
                    $this->mkdirs(APPPATH.'controller/'.$dir_str.DIRECTORY_SEPARATOR);

                } 
                //讀模板內容
                $content_con=$this->controolerTpl(ucwords($controller_v));

                if(!empty($dir_str)) {

                    $file_path=APPPATH.'controllers/'.$dir_str.DIRECTORY_SEPARATOR.ucwords($controller_v).'.php';
                    
                }
                $file_path=APPPATH.'controllers/'.ucwords($controller_v).'.php';

                if (file_exists($file_path)==true) {

                    continue;
                }

                //echo $file_path;
                file_put_contents($file_path, $content_con);

            }
        }

    }


    /**
     * 生成controller模板
     *
     * @param  [type] $controoler_name
     * @return void
     */
    public function controolerTpl($controoler_name)
    {
        $content='';
        $content.="<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\n\n\nclass {$controoler_name} extends MY_Controller\n{\n\n";
        $content.="    public function __construct()\n    {\n        parent::__construct();\n    }\n\n}";
 
        return $content;
    }


    public function modelTpl($model_name)
    {
        $content='';
         $content.="<?php\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\n\n\nclass {$model_name} extends MY_Model\n{\n\n";
        $content.="    public function __construct()\n    {\n        parent::__construct();\n    }\n\n}";

        return $content;

    }


    /**
     * 建立目錄
     *
     * @access protected
     * @param  string $dirname 目錄名稱
     * @return void
     */
    protected static function checkDirBuild($dirname)
    {
        !is_dir($dirname) && mkdir($dirname, 0755, true);
    }


    /**
     * 根據傳入的 build 資料建立目錄和檔案
     *
     * @access public
     * @param  array  $build     build 列表
     * @param  string $namespace 應用類庫名稱空間
     * @param  bool   $suffix    類庫字尾
     * @return void
     * @throws Exception
     */
    public static function run(array $build = [], $namespace = 'app', $suffix = false)
    {
        // 鎖定
        $lock = APP_PATH . 'build.lock';

        // 如果鎖定檔案不可寫(不存在)則進行處理,否則表示已經有程式在處理了
        if (!is_writable($lock)) {
            if (!touch($lock)) {
                throw new Exception(
                    '應用目錄[' . APP_PATH . ']不可寫,目錄無法自動生成!<BR>請手動生成專案目錄~',
                    10006
                );
            }

            foreach ($build as $module => $list) {
                if ('__dir__' == $module) {
                    // 建立目錄列表
                    self::buildDir($list);
                } elseif ('__file__' == $module) {
                    // 建立檔案列表
                    self::buildFile($list);
                } else {
                    // 建立模組
                    self::module($module, $list, $namespace, $suffix);
                }
            }

            // 解除鎖定
            unlink($lock);
        }
    }


    



    /*
    * 建立檔案
    * @access protected
    * @param  array $list 檔案列表
    * @return void
    */
    protected static function buildFile($list)
    {
        foreach ($list as $file) {
            // 先建立目錄
            if (!is_dir(APP_PATH . dirname($file))) {
                mkdir(APP_PATH . dirname($file), 0755, true);
            }

            // 再建立檔案
            if (!is_file(APP_PATH . $file)) {
                file_put_contents(
                    APP_PATH . $file,
                    'php' == pathinfo($file, PATHINFO_EXTENSION) ? "<?php\n" : ''
                );
            }
        }
    }

    /**
     * 迴圈讀取檔案並建立
     * 其實可以不用生成器的 反正就4個檔案 file_Get_content直接讀取 這些檔案 還不到 10kb也挺快的
     */
    public function file_get_contents_write($path)
    {
        foreach($this->_model_arr as $val)
        {
            if(!file_exists($path.strtolower($val).'.txt')) {
                   echo "你的檔案{$this->_model_prefix}{$val}未找到,請放入後檢視";exit(0);
            }
                yield $this->_model_prefix.$val=>file_get_contents($path.strtolower($val).'.txt');
        }
    }


    /**
     * 遞迴建立目錄
     *
     * @param  [type] $dir
     * @return void
     */
    public function mkdirs($dir=null)
    {
        return is_dir($dir) or ($this->mkdirs(dirname($dir))) and mkdir($dir, 0755);
    }


    //在這裡要實現資料庫的話 得呼叫檔案的為 database.php 檔案 

    //還得吧 loader的db檔案拿過來用 這個類 可以在controller後面載入 
    



}