Attributes
Sharing Data
With PSR-7 Http Message Interfaces it is possible to inject objects/values into the request object as attributes using the withAttribute()
method. This method helps us share attributes with middlewares/routes down the order, for example:
$app->addMiddleware(function ($request, $response, $next) { // pass the 'name' attribute to other middleware via the request object $request = $request->withAttribute('name', 'John Doe'); return $next($request, $response); });
Accessing Attributes
The request object exposes attributes passed along with it through the getAttribute()
method:
$app->addMiddleware(function ($request, $response, $next) { // get the 'name' from the request $name = $request->getAttribute('name'); $response->getBody()->write("Hello, $name"); return $next($request, $response); });
Reserved Attributes
The request object accessed via \BitFrame\Application::getRequest()
method, has the following reserved keys that can't be set as an attribute on the request object:
\BitFrame\Data\ApplicationData
: holds shareable application data.\BitFrame\Router\RouteCollectionInterface
: stores shareable route data.
The reserved attributes can be used the same way normal attributes are accessed, like so:
use \BitFrame\Data\ApplicationData; use \BitFrame\Router\RouteCollectionInterface; $app->addMiddleware(function ($request, $response, $next) { // get application data $data = $request->getAttribute(ApplicationData::class); // get application routes data $data = $request->getAttribute(RouteCollectionInterface::class); });