I am using Zend Expressive as an API. I have succeeded adding a middleware, which validates the request headers of API Keys, for every single request.
At the moment I add the middleware using the pipe() function in config/pipeline.php
$app->pipe(new MyAuthMiddleware(....);
This actually works pretty well. However, I would like to add the piping using Zend Servicemanager instead, with a configuration file, like:
return [
'dependencies' => [
/* ... */
'invokables' => [
// Remove this entry:
App\Action\HelloAction::class => App\Action\HelloAction::class,
],
'factories' => [
/* ... */
// Add this:
App\Action\HelloAction::class => App\Action\HelloActionFactory::class,
],
/* ... */
],];
Question: Is it possible to pipe a middleware using Zend Servicemanager? And how if it is.
Yes it's possible. Up to expressive 1.1 it was config driven as you are asking for. Since 1.1 it's programmatic driven by default if you install via the skeleton. You can still use config driven but I have to mention you can't use both. At least, it's not recommended.
A configuration might look like this (taken from an expressive 1.0 expressive app). The error handling changed in 1.1+ but I don't have an example for it.
<?php
return [
'dependencies' => [
'factories' => [
// ...
],
],
'middleware_pipeline' => [
'always' => [
'middleware' => [
Zend\Expressive\Helper\ServerUrlMiddleware::class,
],
'priority' => 10000,
],
'routing' => [
'middleware' => [
Zend\Expressive\Container\ApplicationFactory::ROUTING_MIDDLEWARE,
Zend\Expressive\Helper\UrlHelperMiddleware::class,
LocalizationMiddleware::class,
AuthenticationMiddleware::class,
AuthorizationMiddleware::class,
Zend\Expressive\Container\ApplicationFactory::DISPATCH_MIDDLEWARE,
],
'priority' => 1,
],
'error' => [
'middleware' => [
Application\Middleware\Auth\UnauthorizedErrorMiddleware::class,
Application\Middleware\Auth\ForbiddenErrorMiddleware::class,
Application\Middleware\Logger\ExceptionLoggerMiddleware::class,
],
'error' => true,
'priority' => -10000,
],
],
];
Here is some more info I can find right now: