The HttpKernel Component: HttpKernelInterface

In the conclusion of the second chapter of this book, I've talked about one great benefit of using the Symfony components: the interoperability between all frameworks and applications using them. Let's do a big step towards this goal by making our framework implement HttpKernelInterface:

この本の第 2 章の結論として、Symfony コンポーネントを使用することの大きな利点の 1 つについて説明しました。それは、それらを使用するすべてのフレームワークとアプリケーションの間の相互運用性です。フレームワークに HttpKernelInterface を実装することで、この目標に向けて大きな一歩を踏み出しましょう。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Symfony\Component\HttpKernel;

// ...
interface HttpKernelInterface
{
    /**
     * @return Response A Response instance
     */
    public function handle(
        Request $request,
        $type = self::MAIN_REQUEST,
        $catch = true
    );
}

HttpKernelInterface is probably the most important piece of code in the HttpKernel component, no kidding. Frameworks and applications that implement this interface are fully interoperable. Moreover, a lot of great features will come with it for free.

HttpKernelInterface は、冗談ではなく、おそらく HttpKernel コンポーネントで最も重要なコードです。このインターフェイスを実装するフレームワークとアプリケーションは、完全に相互運用可能です。さらに、多くの優れた機能が無料で付属しています。

Update your framework so that it implements this interface:

このインターフェースを実装するようにフレームワークを更新します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// example.com/src/Framework.php

// ...
use Symfony\Component\HttpKernel\HttpKernelInterface;

class Framework implements HttpKernelInterface
{
    // ...

    public function handle(
        Request $request,
        $type = HttpKernelInterface::MAIN_REQUEST,
        $catch = true
    ) {
        // ...
    }
}

With this change, a little goes a long way! Let's talk about one of the most impressive upsides: transparent HTTP caching support.

この変更により、少しのことが大いに役立ちます。最も印象的な利点の 1 つである、透過的な HTTP キャッシングのサポートについて話しましょう。

The HttpCache class implements a fully-featured reverse proxy, written in PHP; it implements HttpKernelInterface and wraps another HttpKernelInterface instance:

HttpCache クラスは、PHP で書かれた完全な機能を備えたリバース プロキシを実装します。 HttpKernelInterface を実装し、別の HttpKernelInterface インスタンスをラップします。
1
2
3
4
5
6
7
8
9
10
11
12
13
// example.com/web/front.php

// ...
use Symfony\Component\HttpKernel;

$framework = new Simplex\Framework($dispatcher, $matcher, $controllerResolver, $argumentResolver);
$framework = new HttpKernel\HttpCache\HttpCache(
    $framework,
    new HttpKernel\HttpCache\Store(__DIR__.'/../cache')
);

$response = $framework->handle($request);
$response->send();

That's all it takes to add HTTP caching support to our framework. Isn't it amazing?

フレームワークに HTTP キャッシングのサポートを追加するために必要なことはこれだけです。すごいじゃないですか。

Configuring the cache needs to be done via HTTP cache headers. For instance, to cache a response for 10 seconds, use the Response::setTtl() method:

キャッシュの構成は、HTTP キャッシュ ヘッダーを介して行う必要があります。たとえば、応答を 10 秒間キャッシュするには、Response::setTtl() メソッドを使用します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// example.com/src/Calendar/Controller/LeapYearController.php

// ...
public function index(Request $request, $year)
{
    $leapYear = new LeapYear();
    if ($leapYear->isLeapYear($year)) {
        $response = new Response('Yep, this is a leap year!');
    } else {
        $response = new Response('Nope, this is not a leap year.');
    }

    $response->setTtl(10);

    return $response;
}

Tip

ヒント

If you are running your framework from the command line by simulating requests (Request::create('/is_leap_year/2012')), you can debug Response instances by dumping their string representation (echo $response;) as it displays all headers as well as the response content.

リクエスト (Request::create('/is_leap_year/2012')) をシミュレートしてコマンドラインからフレームワークを実行している場合、すべてのヘッダーと返信内容。

To validate that it works correctly, add a random number to the response content and check that the number only changes every 10 seconds:

正しく動作することを検証するには、responsecontent に乱数を追加し、その数が 10 秒ごとにのみ変化することを確認します。
1
$response = new Response('Yep, this is a leap year! '.rand());

Note

ノート

When deploying to your production environment, keep using the Symfony reverse proxy (great for shared hosting) or even better, switch to a more efficient reverse proxy like Varnish.

実稼働環境にデプロイするときは、Symfony リバース プロキシ (共有ホスティングに最適) を使用し続けるか、Varnish などのより効率的なリバース プロキシに切り替えてください。

Using HTTP cache headers to manage your application cache is very powerful and allows you to tune finely your caching strategy as you can use both the expiration and the validation models of the HTTP specification. If you are not comfortable with these concepts, read the HTTP caching chapter of the Symfony documentation.

HTTP キャッシュ ヘッダーを使用してアプリケーション キャッシュを管理することは非常に強力であり、HTTP 仕様の有効期限モデルと検証モデルの両方を使用できるため、キャッシュ戦略を細かく調整できます。これらの概念に慣れていない場合は、Symfony ドキュメントの HTTP キャッシングの章を読んでください。

The Response class contains methods that let you configure the HTTP cache. One of the most powerful is setCache() as it abstracts the most frequently used caching strategies into a single array:

Response クラスには、HTTP キャッシュを構成できるメソッドが含まれています。最も強力なものの 1 つは、最も頻繁に使用されるキャッシング戦略を単一の配列に抽象化する setCache() です。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$response->setCache([
    'must_revalidate'  => false,
    'no_cache'         => false,
    'no_store'         => false,
    'no_transform'     => false,
    'public'           => true,
    'private'          => false,
    'proxy_revalidate' => false,
    'max_age'          => 600,
    's_maxage'         => 600,
    'immutable'        => true,
    'last_modified'    => new \DateTime(),
    'etag'             => 'abcdef'
]);

// it is equivalent to the following code
$response->setPublic();
$response->setMaxAge(600);
$response->setSharedMaxAge(600);
$response->setImmutable();
$response->setLastModified(new \DateTime());
$response->setEtag('abcde');

When using the validation model, the isNotModified() method allows you to cut on the response time by short-circuiting the response generation as early as possible:

検証モデルを使用する場合、 isNotModified() メソッドを使用すると、応答生成をできるだけ早く短縮することで、応答時間を短縮できます。
1
2
3
4
5
6
7
8
9
$response->setETag('whatever_you_compute_as_an_etag');

if ($response->isNotModified($request)) {
    return $response;
}

$response->setContent('The computed content of the response');

return $response;

Using HTTP caching is great, but what if you cannot cache the whole page? What if you can cache everything but some sidebar that is more dynamic that the rest of the content? Edge Side Includes (ESI) to the rescue! Instead of generating the whole content in one go, ESI allows you to mark a region of a page as being the content of a sub-request call:

HTTP キャッシュを使用することは素晴らしいことですが、ページ全体をキャッシュできない場合はどうでしょうか?残りのコンテンツよりも動的な一部のサイドバーを除いて、すべてをキャッシュできるとしたら?エッジ サイド インクルード (ESI) の助けを借りて! ESI では、コンテンツ全体を一度に生成する代わりに、ページの領域をサブリクエスト呼び出しのコンテンツとしてマークすることができます。
1
2
3
4
5
This is the content of your page

Is 2012 a leap year? <esi:include src="/leapyear/2012"/>

Some other content

For ESI tags to be supported by HttpCache, you need to pass it an instance of the ESI class. The ESI class automatically parses ESI tags and makes sub-requests to convert them to their proper content:

ESI タグを HttpCache でサポートするには、それに ESI クラスのインスタンスを渡す必要があります。 ESI クラスは ESI タグを自動的に解析し、サブリクエストを作成して適切なコンテンツに変換します。
1
2
3
4
5
$framework = new HttpKernel\HttpCache\HttpCache(
    $framework,
    new HttpKernel\HttpCache\Store(__DIR__.'/../cache'),
    new HttpKernel\HttpCache\Esi()
);

Note

ノート

For ESI to work, you need to use a reverse proxy that supports it like the Symfony implementation. Varnish is the best alternative and it is Open-Source.

ESI が機能するには、Symfony 実装のように ESI をサポートするリバース プロキシを使用する必要があります。 Varnish は最良の代替手段であり、オープンソースです。

When using complex HTTP caching strategies and/or many ESI include tags, it can be hard to understand why and when a resource should be cached or not. To ease debugging, you can enable the debug mode:

複雑な HTTP キャッシュ戦略を使用したり、多くの ESI インクルード タグを使用したりすると、リソースをキャッシュする必要がある理由とタイミングを理解するのが難しい場合があります。デバッグを容易にするために、デバッグ モードを有効にできます。
1
2
3
4
5
6
$framework = new HttpKernel\HttpCache\HttpCache(
    $framework,
    new HttpKernel\HttpCache\Store(__DIR__.'/../cache'),
    new HttpKernel\HttpCache\Esi(),
    ['debug' => true]
);

The debug mode adds a X-Symfony-Cache header to each response that describes what the cache layer did:

デバッグモードは、キャッシュレイヤーが何をしたかを説明する X-Symfony-Cache ヘッダーを各レスポンスに追加します:
1
2
3
X-Symfony-Cache:  GET /is_leap_year/2012: stale, invalid, store

X-Symfony-Cache:  GET /is_leap_year/2012: fresh

HttpCache has many features like support for the stale-while-revalidate and stale-if-error HTTP Cache-Control extensions as defined in RFC 5861.

HttpCache には、RFC 5861 で定義されているように、stale-while-revalidate および stale-if-error HTTP Cache-Control 拡張機能のサポートなど、多くの機能があります。

With the addition of a single interface, our framework can now benefit from the many features built into the HttpKernel component; HTTP caching being just one of them but an important one as it can make your applications fly!

単一のインターフェイスを追加することで、フレームワークは HttpKernel コンポーネントに組み込まれた多くの機能を利用できるようになりました。 HTTP キャッシングはその 1 つにすぎませんが、アプリケーションを高速化できる重要な機能です。