Skip to content
This repository has been archived by the owner on Jan 21, 2020. It is now read-only.

Allow varying UrlHelper for path-segregated middleware #62

Conversation

weierophinney
Copy link
Member

@weierophinney weierophinney commented Jun 5, 2018

When creating path-segregated middleware, you may want to provide middleware-specific routing. Once you do that, however, you need a new UrlHelper instance that contains that new router, and which knows the base path to prepend, if you want to generate route-specific URIs.

This patch is the first of several that accommodates this scenario.

The approach it uses is to allow optional constructor arguments to each of the UrlHelperFactory and UrlHelperMiddlewareFactory. Usage is as follows:

// in a ConfigProvider or config file:
namespace Api;

use Zend\Expressive\Helper\UrlHelperFactory;
use Zend\Expressive\Helper\UrlHelperMiddlewareFactory;
use Zend\Expressive\Router\FastRouteRouter;

return [
    'dependencies' => [
        'factories' => [
            Router::class => FastRouteRouter::class,
            UrlHelper::class => new UrlHelperFactory('/api', Router::class),
            UrlHelperMiddleware::class => new UrlHelperMiddlewareFactory(UrlHelper::class),
        ],
    ],
];

In the above, Router:class, UrlHelper::class, and UrlHelperMiddleware::class are virtual services, resolving to the Api namespace. When creating our middleware pipeline, we can now reference the UrlHelperMiddleware service:

$app->pipe('/api', [
    Api\UrlHelperMiddleware::class,
    // ...
]);

Each factory now also implements __set_state(), to ensure that configuration caching will work correctly (the default configuration caching uses var_export(), which requires that __set_state() be defined when include is called).

Allows passing the following constructor arguments to the factory:

- base path: the base path to configure on the generated helper
- router service name: the router service name to pull from the
  container when instantiating the helper.

This approach allows re-use of the helper in path-segregated middleware.
Adds a constructor to the `UrlHelperMiddlewareFactory`, allowing passing
the service name of the `UrlHelper` to use when creating the middleware.
This allows using a different `UrlHelper` and related middleware in
path-segregated middleware.
@weierophinney weierophinney merged commit 97e5ec9 into zendframework:develop Jun 5, 2018
@weierophinney weierophinney deleted the feature/allow-varying-factories branch June 5, 2018 15:22
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant