6. Middleware - nathan-fiscaletti/synful GitHub Wiki
Middleware is a tool that provides a convenient mechanism for filtering requests entering your application. For example, Synful includes a middleware that verifies the user of your application is authenticated using an API key. If the user is not authenticated, the middleware will return a 401. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
See APIKeyValidation
Of course, additional middleware can be written to perform a variety of tasks besides authentication. For example, you could use the after
override of a global middleware implementation to add headers to all responses leaving your application.
Pre-Packaged Middleware
Synful comes with pre-packaged middleware that can be applied to achieve different results.
Middlware | Location | Description |
---|---|---|
API Key Validation | \Synful\Util\MiddleWare\APIKeyValidation | Forces API keys for the applied Request Handler |
Creating your own Middleware
To create your own Middleware, run the following command from your command line.
$ ./synful -create-middleware MiddlewareName
This will create a new file in src/Synful/App/MiddleWare
that implements the MiddleWare interface.
Implementing the MiddleWare interface
Each MiddleWare implementation should override the before
and after
functions.
before
- The before function is called before any Request touches it's RequestHandler. This will give you access to both the Request object and the RequestHandler implementation that it is destined for.
Note: Since you have access to the RequestHandler implementation in the
before
function, you can use this to do some fancy things on a Per-RequestHandler basis. For example, add a custom property to your RequestHandler that controls how the middleware will act.See APIKeyValidation for an example of this with the
$white_list_keys
and$security_level
properties.
after
- The after function is called after a RequestHandler has supplied a response to Synful. This will be called directly prior to the Response being sent to the user. It will have access to the response object. This can be useful for modifying headers on a response, or doing anything else to a response.
Applying Middleware
Globally
Global Middleware can be applied through the global_middleware
property of the System.json configuration file.
"global_middleware": [
"\\Synful\\App\\MiddleWare\\MyMiddleWare"
]
Per Request Handler
You can apply middleware on a per-request handler basis. Just override the $middleware
property of your RequestHandler and apply it there.
public $middleware = [
\Synful\Util\MiddleWare\MyMiddleWare::class,
];
Next: Serialization