在独立项目中使用illuminate/database

1. Composer引入

1
2
composer require illuminate/database
composer require illuminate/events

2. 创建DB操作类

文件可以创建为/library/DB.php, 内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

// 注意修改此处的配置
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);

// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

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

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

3. 使用DB操作类

1
DB::table('table_name')->select();

4. 更多操作

https://laravel-china.org/docs/laravel/5.7/database/2288