0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CakePHP 5.3 で設定値取得にアトリビュートが使えるようになっていた件

0
Last updated at Posted at 2026-04-12

この記事でわかること

CakePHP 5.3 から、設定値(Configure)をコンストラクタの引数にそのまま渡すための属性 #[Configure] が使えます。

  • 新しい書き方 : 引数に「この値は Configure のどのキーか」を書く
  • 従来の書き方Configure::read() を自分で呼ぶ必要があった

どちらが「正しい」わけではなく、読みやすさ・チームの運用で選ぶものです。

まず知っておきたいこと

#[Configure] を使うときは「自動解決」をオンにする

#[Configure] は、コンテナが コンストラクタを自動で解釈して(リフレクション)、引数ごとに値をはめる仕組みで動きます。そのため、アプリ側で次の 1行 が必要です。

// In src/Application.php
use League\Container\ReflectionContainer;

public function services(ContainerInterface $container): void
{
    $container->delegate(new ReflectionContainer());
}
  • これがないと、#[Configure('Some.key')] が付いた引数に値が入りません

注意: この行がなくても、Configure::read() を自分で書く従来の方法はこれまでどおり使えます。

パフォーマンス

自動配線は便利ですが、パフォーマンスに影響を与える可能性があります。
本番環境ではキャッシュを有効にしてください(公式の推奨)。

参考: Auto Wiring

従来のやり方

例として、API クライアントに API キーとベース URL を渡すとします。
設定は config/app.phpApi.keyApi.baseUrl がある前提です。

クラスの中で Configure::read() する

namespace App\Service;

use Cake\Core\Configure;

class ApiClient
{
    private string $apiKey;
    private string $baseUrl;

    public function __construct()
    {
        $this->apiKey = (string)Configure::read('Api.key');
        $this->baseUrl = (string)Configure::read('Api.baseUrl');
    }
}
  • 向いている: とにかく早く書きたいとき
  • 注意: 「どの設定キーを読んでいるか」がコンストラクタの型からは見えにくい

新しいやり方:#[Configure]

use Cake\Core\Attribute\Configure;

class ApiClient
{
    public function __construct(
        #[Configure('Api.key')] private string $apiKey,
        #[Configure('Api.baseUrl')] private string $baseUrl,
    ) {
    }
}
  • 向いている: 引数の型とセットで「何が必要か」が見えやすい。

新しい書き方のメリット

依存関係が宣言的になる

このクラスが「どの設定キーを必要としているか」が一目でわかります。
従来の書き方では、メソッドボディを読まないと Configure::read() の呼び出しが把握できませんでした。

テストで差し替えが楽になる

従来の書き方では、クラスが内部で Configure::read() を呼ぶため、
テスト中に特定の値を使わせたい場合は Configure::write() でグローバル状態を操作するしかありません(多分)

// 従来:値を変えたければ Configure を通るしかない
Configure::write('Api.key', 'test-key');
Configure::write('Api.baseUrl', 'https://example.test');
$client = new ApiClient();

新しい書き方ではコンストラクタ引数に直接渡せるので、Configure の状態に関係なく任意の値を注入できます。

// 新しい書き方:Configure の状態を一切触らずに注入できる
$client = new ApiClient(apiKey: 'test-key', baseUrl: 'https://example.test');

まとめ:どちらを選ぶか

  • 小規模なスクリプトや素早くプロトタイプを作るなら従来の書き方で十分
  • チームで保守するサービスクラスやテストを書く場面では、新しい #[Configure] アトリビュートが力を発揮する可能性がある
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?