DBの実装例
Hello Worldの実装をもとに、NaifyDbを追加する例を紹介します。接続設定、ブートストラップでの初期化、Controllerでの読み書き、Viewへの受け渡しを順に見ます。
このページでは追加する処理を紹介します。ファイル配置と公開入口、BaseController、NaifyViewの初期化とgetView()を先に用意します。Controllerとテンプレートを追加したら、対応するURLを routes/routes.php に登録します。
DB接続設定
config/database.php はPHPコードとして定義します。SQLite、MariaDBなど、接続ごとに名前を付けておきます。
use NaifyDb\Adapter\Mysql;
use NaifyDb\Adapter\Sqlite;
return [
'sqlite' => Sqlite::configure()
->database(__DIR__ . '/../_storage/app.sqlite'),
'main' => Mysql::configure()
->host('[db-host]')
->port(3306)
->database('myapp')
->username('[db-user]')
->password('[db-password]')
->charset('utf8mb4'),
];
ブートストラップで読み込む
SampleAppBootstrap.php で、アプリケーション起動時にNaifyDbを初期化し、接続設定を読み込みます。以下はDB初期化部分の抜粋で、Appの生成・ルート読込・run()より前に置きます。libs/NaifyDb も配置しておきます。
use NaifyDb\NaifyDb;
require __DIR__ . '/libs/NaifyDb/NaifyDb.php';
NaifyDb::boot();
NaifyDb::configure()
->loadConfigFile(__DIR__ . '/config/database.php')
->apply();
UserController
ControllerではConnectionからTableを取得し、一覧、詳細、登録などの処理を書きます。
namespace App\Controllers;
use NaifyDb\NaifyDb;
final class UserController extends BaseController
{
public function indexAction(): void
{
$users = NaifyDb::db('main')
->table('users')
->where('active', '=', 1)
->orderBy('id', 'desc')
->get();
$view = $this->getView();
$view->assign('users', $users);
$view->setTemplate('users/index.html');
}
public function detailAction(): void
{
$id = $this->context->getUrlParam('id');
$user = NaifyDb::db('main')->table('users')->findById($id);
if ($user === null) {
$this->context->response->setStatus(404);
echo 'User not found';
return;
}
$view = $this->getView();
$view->assign('user', $user);
$view->setTemplate('users/detail.html');
}
public function createAction(): void
{
NaifyDb::db('main')->table('users')->insert([
'name' => 'Taro',
'email' => 'taro@example.com',
'active' => 1,
]);
header('Location: /users');
}
}
Viewテンプレート
取得した値はNaifyView Nativeのテンプレートへ渡します。HTMLに出す値は通常の変数展開でエスケープされる設計にしておきます。
<h1>ユーザー一覧</h1>
<nf-for-each exp="user in users">
<article>
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
<a href="/users/{{ user.id }}">詳細</a>
</article>
</nf-for-each>