PHPのslim3でEloquent\Modelを使用したモデルの実装

illuminate/databaseはEloquentというORM機能も利用できるのでslim3での利用法を記述

github.com

以下のようにモデルクラスを作成します。

# src/Sample/Model/User.php
<?php
namespace Sample\Model;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
    protected $table = 'user';
    public function getAttribute($key) {
        return parent::getAttribute(\snake_case($key));
    }
    public function setAttribute($key, $value){
        return parent::setAttribute(\snake_case($key), $value);
    }
}

dependencies.phpに「$container->get('db');」の初期化の1行を追加します。

# src/dependencies.php
$container['db'] = function ($c) {
~略~
};
$container->get('db');

コントローラで以下のようにクエリービルダーの形式で記述する事でDBからデータを取得できます

<?php
namespace Sample\Controller;
use Psr\Container\ContainerInterface;
use Sample\Model\User;
class UserController {
    protected $container;
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }
    public function index($request, $response, $args) {
        $users = User::all();
        return $this->container['renderer']->render($response, 'user/index.twig', ['users' => $users]);
    }
}

その他Eloquentのモデルの利用法を以下を参照

Eloquent: Getting Started - Laravel - The PHP Framework For Web Artisans