リクエストハンドラとMVCパターン

リクエストの受け取りからレスポンスまでの流れと、MVCの実装パターン。

RequestContextが中心

RequestContextは、アプリコードが触る標準窓口です。URLパラメータ、リクエスト情報、Cookie、レスポンス設定、ルーティング結果などを1つにまとめて扱います。

Naifyが要求するのはRequestContextHandlerInterfaceによるリクエストハンドラ契約であり、Controllerはその代表的な実装形のひとつです。docsでは、責務分離と見通しのよさがちょうどよい実装パターンとしてMVCを中心に説明します。

RequestContextHandlerInterfaceの契約

Naifyが要求するのはRequestContextHandlerInterfaceの実装です。Controllerはその代表例ですが、責務に応じて別のハンドラ構造を取ることもできます。

namespace Naify\Router;

use Naify\Http\Context\RequestContext;

interface RequestContextHandlerInterface
{
    public function handle(RequestContext $context): void;
}
  • $context: リクエスト情報とレスポンス操作へのアクセス手段
  • 呼び出すメソッド名は$context->routing->getHandlerMethod()で取得します(ルート定義の::以降に書いた名前。例: "indexAction")
  • 戻り値はvoid。出力は$context->responseまたは直接出力で行う
補足: このRequestContextHandlerInterfaceはNaify独自のインターフェースであり、PSR-15のRequestHandlerInterfaceとは別物。

ライフサイクル

Controllerのアクション実行は3フェーズで構成されます。

onActionBefore() → xxxAction() → onActionAfter()
フェーズ役割実装場所
onActionBefore()前処理(認証チェック、共通データ取得など)BaseController
xxxAction()業務処理(ユースケースの調停)Feature Controller
onActionAfter()後処理(テンプレート描画、レスポンス設定など)BaseController

この順序はBaseControllerのhandle()メソッドで固定されます。Feature ControllerはxxxAction()だけを実装すればよく、前後処理のタイミングを気にする必要はありません。

BaseControllerの実装例

アプリ側の実装例です。 プロジェクト側で実装するパターンです。
namespace App\Controllers;

use Naify\Http\Context\RequestContext;
use Naify\Router\RequestContextHandlerInterface;

abstract class BaseController implements RequestContextHandlerInterface
{
    protected RequestContext $context;

    public function handle(RequestContext $context): void
    {
        $this->context = $context;
        // ルート定義の :: 以降に書いたメソッド名(例: indexAction)を受け取る
        $method = $context->routing->getHandlerMethod() ?? 'indexAction';
        $this->onActionBefore();
        $this->{$method}();
        $this->onActionAfter();
    }

    protected function onActionBefore(): void
    {
        //共通前処理をここに書く
    }

    protected function onActionAfter(): void
    {
        //共通後処理をここに書く
    }
}

Feature ControllerはBaseControllerを継承し、アクションメソッドだけを実装します。

namespace App\Controllers;

final class IndexController extends BaseController
{
    public function helloAction(): void
    {
        $name = (string) $this->context->getUrlParam('name', 'World');
        $this->context->response->text("Hello, {$name}!");
    }
}

複数BaseControllerパターン

BaseControllerは1つに集約せず、用途別に分割します。これにより、認証・出力・権限ルールの混在を防げます。

Controllers/ ├── Web/ │ └── BaseController ← HTML出力、CSRF検証 ├── Api/ │ └── BaseController ← JSON出力、Bearerトークン検証 └── Authed/ └── BaseController ← セッション認証、ユーザー注入
アプリ側の実装例です。 プロジェクト側で実装するパターンです。

Web用BaseController

namespace App\Controllers\Web;

use Naify\Http\Context\RequestContext;
use Naify\Router\RequestContextHandlerInterface;

abstract class BaseController implements RequestContextHandlerInterface
{
    protected RequestContext $context;

    public function handle(RequestContext $context): void
    {
        $this->context = $context;
        // ルート定義の :: 以降に書いたメソッド名(例: indexAction)を受け取る
        $method = $context->routing->getHandlerMethod() ?? 'indexAction';
        $this->onActionBefore();
        $this->{$method}();
        $this->onActionAfter();
    }

    protected function onActionBefore(): void
    {
        // CSRFトークン検証など
    }

    protected function onActionAfter(): void
    {
        // View(テンプレート)の描画・出力など
    }
}

API用BaseController

namespace App\Controllers\Api;

use Naify\Http\Context\RequestContext;
use Naify\Router\RequestContextHandlerInterface;

abstract class BaseController implements RequestContextHandlerInterface
{
    protected RequestContext $context;
    protected array $responseData = [];

    public function handle(RequestContext $context): void
    {
        $this->context = $context;
        // ルート定義の :: 以降に書いたメソッド名(例: indexAction)を受け取る
        $method = $context->routing->getHandlerMethod() ?? 'indexAction';
        $this->onActionBefore();
        $this->{$method}();
        $this->onActionAfter();
    }

    protected function onActionBefore(): void
    {
        // Bearerトークン検証など
    }

    protected function onActionAfter(): void
    {
        $this->context->response->json($this->responseData);
    }
}

RequestContextの主要API

コントローラー内でよく使うメソッドの使い方を示します。APIの一覧はリファレンスを参照してください。

パラメータ取得

// 現在のHTTPメソッドに応じた入力パラメータ
$keyword = $this->context->getParam('keyword', '');

// URLパラメータ(ルートの {id} 部分)
$id = (int) $this->context->getUrlParam('id');

// Cookieの取得・設定
$token = $this->context->cookie->get('session_token');
$this->context->cookie->set('theme', 'dark', maxAge: 86400);

リクエスト情報

// HTTPメソッド
$method = $this->context->getMethod();  // "GET", "POST", etc.

// リクエストパス
$path = $this->context->getPath();      // "/users/42"

// リクエストヘッダー・JSONボディ
$accept = $this->context->getRequestHeader('Accept');
$json = $this->context->getRequestJson();

// 検証済みのホスト名
$host = $this->context->server->getHost();

レスポンス操作

// HTML / JSON / テキスト応答
$this->context->response->html('<h1>Hello</h1>');
$this->context->response->json(['ok' => true], 201);
$this->context->response->text('plain text');

// リダイレクト・ダウンロード
$this->context->response->redirect('/login');
$this->context->response->download($filePath, 'report.pdf', 'application/pdf');

ルーティング情報

// ディスパッチ先のハンドラクラス名(FQCN)
$handlerClass = $this->context->routing->getHandlerClass();

// ルート定義の :: 以降に書いたメソッド名(例: 'indexAction')
$method = $this->context->routing->getHandlerMethod();

// ルート名
$name = $this->context->routing->getName();