{"id":19039843,"url":"https://github.com/johnlui/codeigniter-2-with-eloquent","last_synced_at":"2025-04-23T20:49:24.660Z","repository":{"id":22242140,"uuid":"25575484","full_name":"johnlui/CodeIgniter-2-with-Eloquent","owner":"johnlui","description":"CodeIgniter 2.2.0 with Eloquent","archived":false,"fork":false,"pushed_at":"2015-04-03T04:50:24.000Z","size":663,"stargazers_count":42,"open_issues_count":0,"forks_count":13,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-18T05:53:52.968Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://lvwenhan.com/php/414.html","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/johnlui.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-10-22T10:24:22.000Z","updated_at":"2023-07-25T13:53:37.000Z","dependencies_parsed_at":"2022-07-16T17:30:28.128Z","dependency_job_id":null,"html_url":"https://github.com/johnlui/CodeIgniter-2-with-Eloquent","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnlui%2FCodeIgniter-2-with-Eloquent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnlui%2FCodeIgniter-2-with-Eloquent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnlui%2FCodeIgniter-2-with-Eloquent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnlui%2FCodeIgniter-2-with-Eloquent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/johnlui","download_url":"https://codeload.github.com/johnlui/CodeIgniter-2-with-Eloquent/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250513827,"owners_count":21443204,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T22:19:04.170Z","updated_at":"2025-04-23T20:49:24.640Z","avatar_url":"https://github.com/johnlui.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"#给 CI 插上翅膀——在 CodeIgniter 2 中使用 Laravel Eloquent ORM\n\n## 说明\n\n\u003e 原文发表在我的个人网站：[给 CI 插上翅膀——在 CodeIgniter 2 中使用 Laravel Eloquent ORM](http://lvwenhan.com/php/414.html)\n\n##背景介绍\n\nCodeIgniter 框架和 Laravel 框架基本可以看做是之前若干年和这两年的 PHP 框架霸主，使用率和出镜率最高的框架。\n\nCI 是一个轻型框架，只提供了 路由、MVC 分离、视图加载器、Active Record 等一些基本功能，但这恰恰是其使用率高的原因：提供的东西少而精，适用于绝大多数场景。CI 的文档堪称开源软件的典范，非常之清晰、详尽，对新手非常友好，十分容易上手。\n\nLaravel 是这两年刚刚兴起的重型全功能框架，可以极大地提高开发效率，但是 Laravel 4 的文档并没有 3 那么清晰，中文资料也非常少，很多人在学习的时候遇到了比较大的困难。例如复杂的路由系统让很多用惯了 CI 自动映射的人无所适从，文档又只有寥寥几句话，导致相当一部分人被拦在了使用框架的第一步，学习的热情也被浇灭。\n\n我前段时间写了系列教程 [Laravel 4 系列入门教程【最适合中国人的Laravel教程】](http://lvwenhan.com/laravel/398.html)，访问量和反响都还不错，需要的人可以看看。\n\n繁琐的路由让很多人怀念 CI 的自动映射，繁重的框架基础工作（一个 Hello World 页面需要载入 150 多个文件）也让 Laravel 的性能在一些场景下不能满足要求。很多人用了一段时间后发现，Laravel 中的 Eloquent ORM 是跟 CI 比最强大的地方，于是就想把 Eloquent 移植到 CI 上，我以前也想过，无奈实力不够无从下手。现在终于知道怎么搞了，下面我们正式开始。\n\n##基础准备\n\nPHP 版本要求 \u003e= 5.4，这是 Eloquent 的最低要求。\n\n下载 CodeIgniter 2.2.0，地址是 [http://www.codeigniter.com/download](http://www.codeigniter.com/download)，下载完成后解压到某个地方，配置好 HTTP 服务软件，把网站跑起来。如果你已经看到了以下画面，就可以继续往下做了：\n![pic](http://lvwenhan.com/content/uploadfile/201410/6aab1413966279.jpg)\n\n##开始嫁接\n\n我们使用 Composer 来载入和管理 Eloquent。Composer 会生成一个自动加载（`autoload`）文件，我们只需要 `require` 这个文件，就可以使用所有通过 Composer 安装的包。现在我们要在 CodeIgniter 项目中使用 Composer，在其根目录下新建 composer.json：\n\n```json\n{\n  \"require\": {\n    \"php\": \"\u003e=5.4.0\",\n    \"illuminate/database\": \"*\"\n  },\n}\n```\n\n然后运行 `composer update`，稍等片刻，Composer 体系创建完成，同时 illuminate/database 包也已经安装完成。\n\n然后新建 `application/third_party/eloquent.php`：\n\n```php\n\u003c?php\n\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\nuse Illuminate\\Database\\Capsule\\Manager as Capsule;\n\n// Autoload 自动载入\nrequire BASEPATH.'../vendor/autoload.php';\n\n// 载入数据库配置文件\nrequire_once APPPATH.'config/database.php';\n\n// Eloquent ORM\n$capsule = new Capsule;\n\n$capsule-\u003eaddConnection($db['eloquent']);\n\n$capsule-\u003ebootEloquent();\n```\n\n这个文件将会帮我们引入 Composer 的自动加载文件，同时会帮我们初始化 Eloquent，这个文件载入了一个数据库配置文件，在 `application/config/database.php` 的最后新增（注意替换数据库名称和密码）：\n\n```php\n$db['eloquent'] = [\n  'driver'    =\u003e 'mysql',\n  'host'      =\u003e 'localhost',\n  'database'  =\u003e 'ci',\n  'username'  =\u003e 'root',\n  'password'  =\u003e 'password',\n  'charset'   =\u003e 'utf8',\n  'collation' =\u003e 'utf8_general_ci',\n  'prefix'    =\u003e ''\n  ];\n```\n\n接下来我么需要在 CI 应用启动的时候引入上面那个文件，在最外面的 `index.php` 的后部增加：\n\n```php\n/*\n * --------------------------------------------------------------------\n * LOAD Laravel Eloquent ORM\n * --------------------------------------------------------------------\n *\n */\n\nrequire APPPATH.'third_party/eloquent.php';\n```\n\n\u003e 注意，这段代码一定要放在 `require_once BASEPATH.'core/CodeIgniter.php';` 这一行的 ***前面***！\n\n然后，开始使用 Eloquent，修改 `application/controllers/welcome.php` 中的 `index()` 为：\n\n```php\npublic function index()\n{\n  $data['article'] = Article::first();\n  $this-\u003eload-\u003eview('home', $data);\n}\n```\n\n新建 `application/views/home.php` 文件：\n```php\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n  \u003cmeta charset=\"UTF-8\"\u003e\n  \u003ctitle\u003eCI2 with Eloquent\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\n  \u003ch1\u003e\n    \u003c?php echo $article-\u003etitle; ?\u003e\n  \u003c/h1\u003e\n  \u003cdiv class=\"content\"\u003e\n    \u003cp\u003e\n      \u003c?php echo $article-\u003econtent; ?\u003e\n    \u003c/p\u003e\n  \u003c/div\u003e\n\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n现在让我们向数据库中填充需要使用的数据，运行 SQL 语句：\n```sql\nDROP TABLE IF EXISTS `articles`;\n\nCREATE TABLE `articles` (\n  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n  `title` varchar(255) DEFAULT NULL,\n  `content` longtext,\n  PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\nLOCK TABLES `articles` WRITE;\n/*!40000 ALTER TABLE `articles` DISABLE KEYS */;\n\nINSERT INTO `articles` (`id`, `title`, `content`)\nVALUES\n  (1,'我是标题','\u003ch3\u003e我是内容呀~~\u003c/h3\u003e\u003cp\u003e我真的是内容，不信算了，哼~ O(∩_∩)O\u003c/p\u003e'),\n  (2,'我是标题','\u003ch3\u003e我是内容呀~~\u003c/h3\u003e\u003cp\u003e我真的是内容，不信算了，哼~ O(∩_∩)O\u003c/p\u003e');\n\n/*!40000 ALTER TABLE `articles` ENABLE KEYS */;\nUNLOCK TABLES;\n```\n\n然后建立模型，新建 `application/models/Article.php` 文件：\n\n```php\n\u003c?php\n\ndefined('BASEPATH') OR exit('No direct script access allowed');\n\n/**\n* Article Model\n*/\nclass Article extends Illuminate\\Database\\Eloquent\\Model\n{\n  public $timestamps = false;\n}\n```\n\n最后，修改 `composer.json` 将 models 文件夹加入自动加载：\n\n```json\n{\n  \"require\": {\n    \"php\": \"\u003e=5.4.0\",\n    \"illuminate/database\": \"*\"\n  },\n  \"autoload\": {\n    \"classmap\": [\n      \"application/models\"\n    ]\n  }\n}\n```\n\n运行 `composer dump-autoload`，刷新页面！你将看到以下画面：\n\n![pic](http://lvwenhan.com/content/uploadfile/201410/76b01413970486.jpg)\n\n**恭喜你！Eloquent 嫁接到 CodeIgniter 2 成功！**\n\nCodeIgniter 3 正处于 DEV 阶段，原生支持 Composer，可以直接修改 composer.json 文件，配置方式和 2 完全一致。\n\n##资源汇总\n\n1. CodeIgniter 2 with Eloquent，GitHub 地址：[https://github.com/johnlui/CodeIgniter-2-with-Eloquent](https://github.com/johnlui/CodeIgniter-2-with-Eloquent)\n2. [利用 Composer 一步一步构建自己的 PHP 框架（四）——使用 ORM](http://lvwenhan.com/php/409.html)\n3. [Eloquent 中文文档](http://laravel-china.org/docs/eloquent)\n4. [Download CodeIgniter](http://www.codeigniter.com/download)\n5. [illuminate/database](https://github.com/illuminate/database)\n\n### License\n\nCodeIgniter-2-with-Eloquent is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnlui%2Fcodeigniter-2-with-eloquent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnlui%2Fcodeigniter-2-with-eloquent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnlui%2Fcodeigniter-2-with-eloquent/lists"}