★わ浪漫少帅 发表于 2015-6-30 11:32:29

让CI变成VC架构吧!

本帖最后由 ★わ浪漫少帅 于 2015-6-30 12:15 编辑

我想有些童鞋经常会因为在Codeigniter中写一些重复的model而烦扰吧,或者这些model只是为了跟数据库打交道而写,因为Codeigniter是一个MVC架构,如果在Controller中就能通过一个方法自动加载想要的model而无需在models文件夹写model那岂不是方便吗?因此我将Codeigniter的MVC架构改成了VC架构,接下来我将详细讲解过程:

第一步:这也是核心步骤,在system/core/Controller.php添加关键的1个函数:
function model($class, $conditions = array())
    {
      if ( ! class_exists('CI_Model'))
      {
          load_class('Model', 'core');
      }
      $model = ucfirst($class);
      if(file_exists(FCPATH.APPPATH.'models/'.$model.'_model'.EXT)){                        
            $model = $model . '_model';
            $this->load->model($model);
            return $this->$model;
      }
      if(class_exists($class)){
            return new $class();
      }
      $base_model = $this->config->item('default_base_model');
      $base_model = empty($base_model) ? ' extends CI_Model' : ' extends '. $base_model;
      $db = isset($conditions['db']) ? $conditions['db'] : 'default';
      $id = isset($conditions['id']) ? $conditions['id'] : 'id';
            $tmp_class =
            <<<EOT
            class {$model}{$base_model}{
                  public function __construct() {
                            \$this->_db = '{$db}';
                            \$this->primary_key = '{$id}';
                            parent::__construct();
                  }
            }
EOT;
      eval($tmp_class);
      return new $model();
    }      
第二步:在application/config/config.php中最后一行加入一句配置参数:
$config['default_base_model'] = 'MY_Model';

如果有在core中重构CI Model的话可以在这里写重构的Model名称否则留空

Example:
public function test(){
      // 原生的用法
      $test[] = $this->model('users')->query('select * from users')->result_array();                // 使用MY_Model的用法
      $test[] = $this->model('users')->get_all();
      // 默认使用主键和切库只支持MY_Model, MY_Model可以下载以下链接中的附件:http://codeigniter.org.cn/forums ... 950&page=1#pid80690
      $test[] = $this->model('users', array('primary_key' => 'id', 'db' => 'test'))->get_all();
      //    如果你还是在models文件里面建立了user_model.php, 并且里面有一个test方法
      $test[] = $this->model(users')->test();
         var_dump($test);
    }
有什么疑问可以在CI群中找我:群qq:256269683 群昵称:Ⅱ、执笔写年华








★わ浪漫少帅 发表于 2015-6-30 11:42:30

有什么疑问可以在CI群中找我:

★わ浪漫少帅 发表于 2015-6-30 11:44:18

有什么疑问可以在CI群中找我:群qq:256269683 群昵称:Ⅱ、执笔写年华

Closer 发表于 2015-6-30 13:50:41

不太懂意義在哪
autoload 不是可以自動加載 model?
页: [1]
查看完整版本: 让CI变成VC架构吧!