用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2900|回复: 2
收起左侧

[Others] Codeigniter MVC ->VC | MVC

[复制链接]
发表于 2013-11-13 16:33:07 | 显示全部楼层 |阅读模式
本帖最后由 ★わ浪漫少帅 于 2013-11-13 16:37 编辑

链接:https://github.com/ym1623/codeigniter-restserver
当你用codeigniter的时候是否为经常写一些model而烦扰呢?
现在你无需担心,你写的任何任何控制器都会自动载入相应的model,这些model都在控制器加载完毕后载入, 只会加载一次.
实现在controller中自动载入model的核心代码,无需在models文件夹写model文件
PHP复制代码
 
        /**
         * You can control the $auto_model rest.php to control whether to automatically load model
         */

        protected function _init_load_model(){
                static $_class;
                self::$instance =& $this;
                $class = self::$instance->router->class;
                if (isset($_class))
                {
                        return $this->{$class} = $_class[0];
                }
                switch ($this->config->item('auto_model')) {
                        case 'auto':
                                $this->{$class} = $this->model($class);
                                break;
                       
                        default:
                                $this->{$class} = $this->load->model($class.'_model');
                                break;
                }
                $_class[0] =& $this->{$class};
        }
 
        function model($class){
                load_class('Model', 'core');
                $model = ucfirst($class).'_Model';
                $db = isset($this->_db) ? $this->_db : 'default';
                $id = isset($this->id) ? $this->id : 'id';
                $tmp_class =
                <<<EOT
                class {$model} extends MY_Model{
                        public function __construct() {
                                \$this->_db = '{$db}';
                                \$this->primary_key = '{$id}';
                                parent::__construct();
                        }
                }
EOT
;
                eval($tmp_class);
                return $this->$class = new $model();
        }
 
复制代码


调用例子:
PHP复制代码
class Examples extends REST_Controller
{
  //如果使用database.php的默认数据库,则不用写该构造函数
    /*function __construct()
    {
       //默认使用的database
        $this->_db = '';
       //默认使用的database 的键值
        $this->primary_key = 'id';
        parent::__construct();
    }*/

//默认已经加载当前控制器的model
    public function model_get(){
        $data = $this->example
            ->select('*')
            ->join('example2', 'example.id = example2.id')
            ->get_all();
        $this->res(array('data' => $data));
    }
//加载其他model层的时候
    public function model2_get(){
        $data = $this->model('example2')->get_all();
        $this->res(array('data' => $data));
    }
}
复制代码



发表于 2013-11-14 12:57:56 | 显示全部楼层
顶一个,看看先。{:soso_e104:}
 楼主| 发表于 2013-11-14 13:16:16 | 显示全部楼层
hasylu 发表于 2013-11-14 12:57
顶一个,看看先。

这个是REST API codeigniter的代码,Codeigniter的代码修改的我也分享了:http://codeigniter.org.cn/forums/thread-17950-1-1.html

本版积分规则