Skip to content

Add support for named parameter handler resolving.#41

Closed
matt-allan wants to merge 1 commit intomrjgreen:masterfrom
matt-allan:named-parameter-handler
Closed

Add support for named parameter handler resolving.#41
matt-allan wants to merge 1 commit intomrjgreen:masterfrom
matt-allan:named-parameter-handler

Conversation

@matt-allan
Copy link

Hello,

This PR adds support for Handler Resolvers that would prefer to receive an associative array where name => value for parameters.

I am using PHP DI for dependency injection which is able to inject parameters by matching the name. Passing an associative array of arguments means I can write a handler resolver like this:

class RouteHandlerResolver implements NamedParameterHandlerResolverInterface
{
    //...
    public function resolve($handler)
    {
        if (is_array($handler) && is_string($handler[0])) {
            $handler[0] = $this->container->get($handler[0]);
        }

        $handler = function ($args) use ($handler) {
            return $this->container->call($handler, $args);
        };

        return $handler;
    }
}

Which allows using routes like this:

$router->get('/hello/{name}', function (Request $request, Response $response, $name) {
    $response->setContent("hello {$name}!");
    return $response;
});

I wrote a separate interface to allow adding this behavior without causing any backwards compatibility breaks. You can simply implement the regular HandlerResolverInterface if you do not want a single array of named parameters.

Let me know if this is something you would be interested in adding to the library.

Thanks!

@mattsah
Copy link

mattsah commented Oct 5, 2016

@mrjgreen are you still maintaining this project? I'd like to second this request as I could use this feature (currently just relying on a hacked fork).

@rougin
Copy link

rougin commented May 31, 2017

Hello @mattsah . Can I ask if you rewrite the whole Dispatcher class to fork it? I can't extend the said class for now because its visibility for non-public methods is private.

@mattsah
Copy link

mattsah commented May 31, 2017

@rougin sorry, I essentially abandoned this for AltoRouter -- which had its own set of limitations too. Unfortunately despite having probably 500 routers, the PHP community has few that cover the actual real world uses of routers and are open to active maintenance and development.

@arryanggaputra
Copy link

@mrjgreen do you mind to merge this request?

@matt-allan matt-allan closed this Dec 12, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants