Codeigniter 3 整合 Eloquent ORM 操作记录

虽然这里已经荒了很久,偶尔还是来拔拔草。

最近的小项目选用的CodeIgniter。虽然一直被推荐用laravel,但homestead实在是用不惯。还是那种直接从官网下载个tar.gz包,往web文件夹里一丢就能跑起来的简单粗暴方法合适我。

但Laravel中的Eloquent ORM公认好用。来想办法将这货整合到CodeIgniter3中吧。下面是操作流程。

1、安装CodeIgniter 和 Composer

这个就不赘述了,CodeIgniter基本就是下载压缩包后解压的动作。Composer的安装按照官网走。

2、在CodeIgniter的项目目录中,添加composer.json 如下:

{
  "require":{
    "illuminate/database":"5.2.37"
  }
}

3、执行” composer install “安装之。

4、编辑CodeIgniter的index.php入口文件的末尾,添加autoload部分:

/*
 * load the composer autoload file.
 */

require_once "../../vendor/autoload.php";

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 */
require_once BASEPATH.'core/CodeIgniter.php';

5、在CodeIgniter中的配置和初始化Eloquent.修改 config/database.php 如下:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager as Capsule;

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
   'dsn'  => '',
   'hostname' => 'localhost',
   'username' => '',
   'password' => '',
   'database' => '',
   'dbdriver' => 'mysqli',
   'dbprefix' => '',
   'pconnect' => FALSE,
   'db_debug' => (ENVIRONMENT !== 'production'),
   'cache_on' => FALSE,
   'cachedir' => '',
   'char_set' => 'utf8',
   'dbcollat' => 'utf8_general_ci',
   'swap_pre' => '',
   'encrypt' => FALSE,
   'compress' => FALSE,
   'stricton' => FALSE,
   'failover' => array(),
   'save_queries' => TRUE
);

$capsule = new Capsule;
$capsule->addConnection([
   'driver'    => 'mysql',
   'host'      => $db['default']['hostname'],
   'database'  => $db['default']['database'],
   'username'  => $db['default']['username'],
   'password'  => $db['default']['password'],
   'charset'   => $db['default']['char_set'],
   'collation' => $db['default']['dbcollat'],
   'prefix'    => $db['default']['dbprefix'],
]);

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

?>
6、修改application/config/autoload.php,将database自动加载
$autoload['libraries'] = array('database');
7、让我们来写个继承自Eloquent的Model。 其中users表结构请自行脑补。
<?php
use \Illuminate\Database\Eloquent\Model as Eloquent;
class Test_eloquent extends Eloquent {
    protected $table = "users";   
}
?>
8、再写一个Controller。
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TestController extends CI_Controller {
    public function index(){
        $this->load->model("Test_eloquent");
        $users = Test_eloquent::all();
        foreach($users as $user){
            echo $user->username."<br>";
        }
    }
}
?>
9、好了,打开浏览器: http://localhost/TestController 看看结果吧

Happy Coding.