在 Laravel 框架之外使用数据库查询构建器及 Eloquent ORM

WBOY
Release: 2016-06-20 12:40:20
Original
1175 people have browsed it

在Laravel 框架核心代码的 illuminate/database包中,有一个 Capsule目录, 该目录下有一个 Manager.php文件,如果要在 Laravel 之外使用 Illuminate Database 组件,就要通过该文件实现。以Yii2 为例,我们首先在项目根目录下运行使用如下 Composer 命令安装该依赖包:

composer require illuminate/database ~5.1
Copy after login

这样在 vendor目录下现在就有了 illuminate/database包,接下来我们修改入口文件 index.php如下:

<?php// comment out the following two lines when deployed to productiondefined('YII_DEBUG') or define('YII_DEBUG', true);defined('YII_ENV') or define('YII_ENV', 'dev');require(__DIR__ . '/../vendor/autoload.php');require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');//引入加载 Eloquent ORM 的启动文件require((__DIR__.'/../system/eloquent/Start.php');$config = require(__DIR__ . '/../config/web.php');(new yii\web\Application($config))->run();
Copy after login

然后我们到项目根目录下创建 system/eloquent/Start.php,编辑文件内容如下:

<?php$database = [    'driver' => 'mysql',    'host' => DB_HOST,    'database' => DB_NAME,    'username' => DB_USER,    'password' => DB_PASSWORD,    'charset' => 'utf8',    'collation' => 'utf8_unicode_ci',    'prefix' => DB_TABLEPREFIX,];use Illuminate\Container\Container;use Illuminate\Database\Capsule\Manager as Capsule;$capsule = new Capsule;// 创建链接$capsule->addConnection($database);// 设置全局静态可访问$capsule->setAsGlobal();// 启动Eloquent$capsule->bootEloquent();
Copy after login

最后,我们可以到 models目录下创建模型类如下:

<?phpnamespace app\models;use Illuminate\Database\Eloquent\Model;class User extends Model{    protected $table = 'user';}
Copy after login

这样我们就可以在代码中以 Eloquent 模型类的语法使用 User 模型了。关于 Eloquent ORM 的使用方法,可参考Eloquent ORM 文档。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!