All jobs

Add HTTP Response Caching to a Slim 4 App

Yes. An agent adds Cache-Control and ETag headers to your Slim 4 app with slim/http-cache, answers 304 to matching requests, tests it, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how the app is wired before it adds a header. In an app laid out like slimphp/Slim-Skeleton, composer.json requires slim/slim ^4.12, slim/psr7 ^1.6, php-di/php-di ^6.4 and monolog/monolog ^2.9 on PHP ^7.4 || ^8.0, with phpunit/phpunit ^9.6.17, phpstan/phpstan ^1.10 and squizlabs/php_codesniffer ^3.9 for development. public/index.php builds the PHP-DI container from app/settings.php, app/dependencies.php and app/repositories.php, then loads app/middleware.php, which adds only SessionMiddleware, and app/routes.php, which serves /, an OPTIONS catch-all, and a /users group with ListUsersAction and ViewUserAction. Every action extends App\Application\Actions\Action, whose respond method JSON-encodes an ActionPayload with JSON_PRETTY_PRINT and sets Content-Type: application/json. InMemoryUserRepository holds five users, so both routes return the same bytes on every request and are a clean case for conditional requests. .github/workflows/tests.yml runs phpcs, phpstan (level 4 over src, from phpstan.neon.dist) and phpunit on PHP 7.4 to 8.2.

The package is slim/http-cache (1.3.0 on Packagist, requiring psr/http-message ^1.1 || ^2.0 and psr/http-server-middleware ^1.0, so it fits this PHP range). Its Slim\HttpCache\Cache middleware is PSR-15: its constructor takes a type (private by default), a max age in seconds (86400 by default) and a must-revalidate flag. After the handler runs, it adds Cache-Control: <type>, max-age=<n> when the response has none (or no-cache when the max age is 0), and it answers 304 when the response carries an ETag that appears in the request's If-None-Match list, or a Last-Modified no later than If-Modified-Since. The agent registers it in app/middleware.php as $app->add(new Cache('public', 0)) by default, so nothing is cached by proxies until the reader chooses a max age, and reads the type and max age from a new cache entry in app/settings.php next to the logger settings so they are one place to change.

Headers that make the 304 path work come from Slim\HttpCache\CacheProvider, which the agent registers in app/dependencies.php and injects into Action. In respond, after the JSON is encoded, it sets a strong ETag from a hash of the payload with withEtag($response, $hash), which quotes the value for you. The agent chooses a hash over withLastModified because the in-memory repository has no timestamps; a repository with an updated_at column would get withLastModified as well, and the pull request shows where. Responses with a status other than 200 are left without an ETag, so the error handler's output is never served from a cache.

Tests follow the skeleton's own pattern: tests/Application/Actions/User/ListUserActionTest.php builds the app with getAppInstance, replaces UserRepository with a Prophecy mock and compares the JSON body. The agent adds a test that reads the ETag from a first /users request, sends a second with If-None-Match set to it, and asserts status 304 and a Cache-Control header, plus one that asserts a /users/{id} for an unknown id carries no ETag. It runs vendor/bin/phpcs, vendor/bin/phpstan and vendor/bin/phpunit in the sandbox, the same three commands as CI, and fixes the level 4 findings that typed injection into Action tends to raise before it opens the pull request.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add HTTP response caching to this Slim 4 app with slim/http-cache. Read composer.json, public/index.php, app/settings.php, app/dependencies.php, app/middleware.php, app/routes.php, src/Application/Actions/Action.php, the user actions, the in-memory repository, tests/TestCase.php and the existing action tests first. Require slim/http-cache, register the Cache middleware in app/middleware.php with a type and max age read from a new cache entry in app/settings.php (default public and 0), register CacheProvider in the container, and set a strong ETag from a hash of the encoded payload in Action::respond for 200 responses only. Add tests that a second request with If-None-Match answers 304 with a Cache-Control header and that an error response carries no ETag. Run phpcs, phpstan and phpunit until all three pass, and open a pull request that quotes their output and shows the headers of one cached response.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request changes composer.json and composer.lock, app/settings.php, app/dependencies.php, app/middleware.php and src/Application/Actions/Action.php, and adds two tests under tests/Application/Actions/User/. Its description shows the response headers of a /users request and the 304 that follows it, quotes the phpcs, phpstan and phpunit output from the sandbox, and explains why the default max age is 0 and what changing it to a positive number does to shared caches.

A reviewer checks that the ETag is computed from the final bytes (after JSON_PRETTY_PRINT, so a formatting change invalidates it), that SessionMiddleware and the new Cache middleware are in an order that leaves the session untouched on a 304, and that the cache settings read sensibly in production, where displayErrorDetails already has a note to flip.

From then on a client that sends If-None-Match gets a 304 and no body for an unchanged list, and the max age is a one-line change in app/settings.php once the team decides what a proxy may keep.

Run it on every Slim service repository

A team with several Slim services sends this body once per repository from its own server, each POST /o/{org}/sessions with that repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own service: one whose repository returns timestamps gets Last-Modified as well, and one that already sets Cache-Control on a route keeps that route's header, because the middleware leaves an existing one alone.

An automation on the Project with a github trigger on pull_request.opened and the prompt "if this pull request adds a GET action, check that its 200 response carries an ETag through Action::respond and that there is a test for the 304 path, and post a review" runs once per pull request. The trigger adds the pull request after the prompt and fills in nothing else. Only work by an owner, member or collaborator fires it.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

Caching headers are cheap to add and expensive to get wrong: a public max age on a personalised response or an ETag on an error page serves the wrong body to the wrong person for a day. The agent reads the actions and the error handler before it touches respond, keeps the default max age at 0, writes the 304 test, and runs the same three checks as the repository's CI in its own sandbox, keeping every command and its output with the pull request.

A reviewer reads one middleware line, one method change and two tests, with the headers of a real response in front of them. A team with several services starts the same request across all of them at once.

Frequently asked questions

Why is the default max age 0?

With max-age=0 the middleware sends Cache-Control: public, no-cache, so clients and proxies revalidate every time and the ETag does the work. Raising it is a one-line change in app/settings.php, and the pull request explains what a positive value lets a shared cache keep.

Does this work with PHP 7.4?

Yes. slim/http-cache 1.3.0 requires PHP ^7.2 || ^8.0 and PSR-15 middleware, both of which the skeleton already has, and the workflow's 7.4 job runs the new tests like the others.

What about Last-Modified?

The in-memory repository has no timestamps, so there is nothing truthful to put in that header. The pull request shows where withLastModified goes in respond for a repository that returns an updated_at, and the middleware already answers 304 to If-Modified-Since when the header is present.

Will the session middleware interfere?

No. SessionMiddleware starts the session and passes through; the Cache middleware wraps the handler's response and only compares headers. The agent keeps the order explicit in app/middleware.php and a test covers the 304 path through both.

More Slim jobs

The same job on other stacks

Keep reading