実践:MVCパターンで書く
ブートストラップから基本設定、ルート定義、BaseController戦略、コントローラーの実装まで、MVCパターンでアプリケーションを組み立てる実践例です。
1. ディレクトリ構成と公開入口
Webサーバーの公開ディレクトリ(public_html)には入口となるindex.phpと静的ファイルだけを置きます。Naify本体(vendor/naify)、起動ファイル、ルート、コントローラー、View、キャッシュなど外部に見せてはいけないファイルはすべて公開領域の外側(非公開ディレクトリ)に配置します。
[project]/
├── public_html/ # Web公開ディレクトリ(外部からアクセス可)
│ └── index.php # フロントコントローラー
├── _cache/ # キャッシュ・ログ領域(非公開)
│ └── app_main/
│ └── views/
└── _apps/ # 非公開アプリケーション領域
├── vendor/naify/ # Naify 本体(非公開)
└── app_main/
├── NaifyBootstrap.php # 起動・基本設定
├── routes/
│ └── routes.php # ルート定義
├── src/
│ └── Controllers/
│ ├── BaseController.php
│ └── UserController.php
└── views/
└── users/
├── index.html
└── show.html
public_html/index.phpには処理を書かず、非公開領域にあるNaifyBootstrap::run()を呼び出すだけにとどめます。
<?php
declare(strict_types=1);
// 非公開領域のブートストラップを読み込んでアプリを実行する
require_once dirname(__DIR__) . '/_apps/app_main/NaifyBootstrap.php';
\App\NaifyBootstrap::run();
2. ブートストラップとNaifyの基本設定
起動処理は_apps/app_main/NaifyBootstrap.phpにまとめ、設定とアプリの組み立てを行うcreate()と、実行と最終例外の捕捉を行うrun()に分けます。Naify::createConfig()で実行環境・ディレクトリ・ベースパスを明示します。
<?php
declare(strict_types=1);
namespace App;
use Naify\App\App;
use Naify\Naify;
use NaifyView\NaifyView;
final class NaifyBootstrap
{
public static function create(): App
{
// 1. 相対パスの基準を app_main/ に固定し、非公開領域のパッケージを起動する
chdir(__DIR__);
$appsRoot = dirname(__DIR__);
$projectRoot = dirname(__DIR__, 2);
$vendorNaify = $appsRoot . '/vendor/naify';
require_once $vendorNaify . '/Naify/Naify.php';
require_once $vendorNaify . '/NaifyView/NaifyView.php';
Naify::boot();
NaifyView::boot();
// 2. アプリケーション名前空間の登録
Naify::autoload('App', __DIR__ . '/src');
// 3. Naify の基本設定(AppConfig)
$publicDir = trim((string) ($_SERVER['DOCUMENT_ROOT'] ?? ''));
if ($publicDir === '' || !is_dir($publicDir)) {
$publicDir = $projectRoot . '/public_html';
}
$config = Naify::createConfig()
->setEnvironment('production') // 実行環境(production / development 等)
->setDebugMode(false) // 本番では詳細エラーを出さない
->setPublicDir($publicDir) // 公開ディレクトリの場所
->setCacheDir($projectRoot . '/_cache/app_main', createDir: true) // キャッシュ保存先(なければ自動作成)
->setBasePath((string) ($_SERVER['SCRIPT_NAME'] ?? '/')); // サブディレクトリ配置にも対応
// 4. NaifyView の設定(テンプレート置き場とコンパイル済みキャッシュ先)
NaifyView::configure([__DIR__ . '/views'])
->setCacheDir($config->getCacheDir() . '/views');
// 5. アプリ生成とルート読み込み
$app = Naify::createApp($config);
$app->loadRoute('routes/routes.php');
return $app;
}
public static function run(): void
{
try {
// リクエストを処理してレスポンスをブラウザへ返す
$app = self::create();
$response = $app->run();
$app->emit($response);
} catch (\Throwable $e) {
// 想定外の例外はログに記録し、画面には安全な文言だけを出す
error_log($e->getMessage());
http_response_code(500);
echo 'ページを表示できませんでした。';
}
}
}
3. ルート設定
createRouteFactory()でコントローラーの名前空間を指定し、URLと「コントローラー::メソッド」を結びつけます。サブ名前空間は.で区切り、名前付きルート(setName())を付けておくとリンクやリダイレクト先の管理がしやすくなります。
<?php
declare(strict_types=1);
use Naify\Router\Router;
return static function (Router $router): void {
// コントローラーの名前空間の共通部分をあらかじめ登録する
$to = $router->createRouteFactory('App\\Controllers\\');
// 通常の画面・一覧・詳細(setName() で名前付きルートにしておくと URL 生成に使える)
$router->get('/', $to('HomeController::indexAction'))
->setName('home');
$router->get('/users', $to('UserController::indexAction'))
->setName('users.index');
$router->get('/users/{id}', $to('UserController::showAction'))
->setName('users.show');
// サブ名前空間を使う場合はドット(.)で区切る(App\Controllers\Admin\DashboardController)
$router->get('/admin', $to('Admin.DashboardController::indexAction'))
->setName('admin.dashboard');
// 404などのエラーハンドラを登録する
$router->error('*', $to('ErrorController::indexAction'));
};
4. BaseController戦略
BaseControllerでRequestContextHandlerInterfaceを実装し、前処理(onActionBefore())→ Action本体 → 後処理(onActionAfter())の流れを固定します。ログイン確認や画面共通の初期化などはミドルウェアに分散させず、BaseControllerへ集約します。
<?php
declare(strict_types=1);
namespace App\Controllers;
use Naify\Http\Context\RequestContext;
use Naify\Router\RequestContextHandlerInterface;
use NaifyView\NaifyView;
use NaifyView\View\View;
abstract class BaseController implements RequestContextHandlerInterface
{
protected RequestContext $context;
private ?View $view = null;
// Router から呼ばれる入口。前処理 → Action → 後処理 の順に実行する
public function handle(RequestContext $context): void
{
$this->context = $context;
// ルート定義の :: 以降に指定したメソッド名を取り出す
$method = $context->routing->getHandlerMethod() ?? 'indexAction';
$this->onActionBefore();
$this->{$method}();
$this->onActionAfter();
}
protected function onActionBefore(): void
{
// 認証チェックや共通データの準備を置く
}
protected function onActionAfter(): void
{
// テンプレートが設定されていれば自動描画してレスポンスにセットする
if ($this->view !== null && $this->view->getTemplate()) {
$this->context->response->html($this->view->render());
}
}
// 必要なときに1度だけ View を作って使い回す
protected function getView(): View
{
return $this->view ??= NaifyView::create();
}
}
用途別の分割戦略
画面が増えても1つのBaseControllerにすべてを詰め込まず、役割ごとに基底クラスを分けると見通しを保てます。
src/Controllers/
├── BaseController.php # 公開Web画面向け(HTML描画・共通初期化)
├── Api/
│ └── BaseController.php # API向け(JSON応答・トークン検証)
└── Authed/
└── BaseController.php # 会員/管理画面向け(onActionBefore でログイン確認)
5. 実際のコントローラー
BaseControllerを継承した各コントローラーは、リクエスト値の受け取り・処理の呼び出し・Viewへの受け渡し(またはリダイレクト応答)に集中します。
<?php
declare(strict_types=1);
namespace App\Controllers;
final class UserController extends BaseController
{
/**
* ユーザー一覧を表示する
*
* @naify-route GET /users
*
* @return void
*/
public function indexAction(): void
{
$users = [
['id' => 1, 'name' => '山田 太郎'],
['id' => 2, 'name' => '鈴木 花子'],
];
// テンプレートへ値を渡し、表示するHTMLファイルを指定する
// (実際の描画と出力は BaseController::onActionAfter() が自動で行う)
$view = $this->getView();
$view->assign('users', $users);
$view->setTemplate('users/index.html');
}
/**
* ユーザー詳細を表示する
*
* @naify-route GET /users/{id}
*
* @return void
*/
public function showAction(): void
{
// URLの {id} を受け取る
$id = (int) $this->context->getUrlParam('id', '0');
if ($id <= 0) {
// 名前付きルートからURLを組み立てて一覧へリダイレクトする
$this->context->response->redirect($this->context->urlFor('users.index'));
return;
}
$view = $this->getView();
$view->assign('userId', $id);
$view->assign('userName', '山田 太郎');
$view->setTemplate('users/show.html');
}
}