3. 資料庫 database & Eloquent ORM

ZouZhipeng發表於2021-02-23

composer 引入相關包

composer require illuminate/database
composer require doctrine/dbal
composer require illuminate/events

建立配置檔案,並在專案的入口檔案引入

例如 orm.php, 入口檔案 index.php 的地方就是 include "orm.php";

<?php

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;

// 自己配置
$admin = [
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'database' => 'test',
    'username' => 'root',
    'password' => 'secret',
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'port' => '3306',
    'prefix' => '',
];

$sdk = [
    'driver' => 'mysql',
    'host' => '',
    'database' => '',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
];

$capsule = new Capsule();
// 建立連結(多庫配置)
$capsule->addConnection($admin, 'default');
$capsule->addConnection($sdk, 'sdk');
// 資料庫查詢事件
$capsule->setEventDispatcher(new Dispatcher(new Container()));

// 設定全域性靜態可訪問
$capsule->setAsGlobal();

Capsule::connection('default')->listen(function ($query) {
    // 這裡是執行 sql 後的監聽回撥方法
    $sql = vsprintf(str_replace("?", "'%s'", $query->sql), $query->bindings) . " [" . $query->time . ' ms] ';
    // 把 SQL 寫入到日誌檔案中
//    Debug::log($sql, 'info');
});
// 啟動 Eloquent
$capsule->bootEloquent();

使用 Query Builder index/orm.php

<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../orm.php';

use App\Eloquent\User;
use Illuminate\Database\Capsule\Manager as DB;

$users = DB::connection('default')->table('users')->where('id', '>', 1)->take(2)->get();
dd($users);

使用 Eloquent ORM

新建 Eloquent Model src/Eloquent/User.php

<?php

namespace App\Eloquent;

use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent
{
    protected $table = 'users';
}

index/orm.php

<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../orm.php';

use App\Eloquent\User;
use Illuminate\Database\Capsule\Manager as DB;

$users = User::all();
dd($users);

命令列開啟服務 php -S localhost:8000 並訪問 http://localhost:8000/index/orm.php 即可。

專案目錄結構

.
├── composer.json
├── composer.lock
├── config
├── helpers
│   └── laravel_helpers.php
├── index
│   ├── dd.php
│   ├── orm.php
│   └── validator.php
├── lang
│   └── zh_cn
│       └── validation.php
├── orm.php
└── src
    ├── Eloquent
    │   └── User.php
    └── Handlers
        └── Validator.php

參考 致謝

  1. 在非 laravel 專案中引入 Illuminate\Database
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章