nikic / FastRoute

Fast request router for PHP
Other
5.13k stars 445 forks source link

Using a Class and its method as handler. #214

Closed ghost closed 4 years ago

ghost commented 4 years ago

I am trying to use this router library to instantiate a class and use a method in it. only my view class work i.e when i render a view as the handler but i also want to use a method of a class as handler e.g addrouter->('GET', '/login', LoginControllerClass/indexAction). i mean i want this upon execution to instantiate the login controller class and call the indexAction method in the class. please, i am a novice in term of routing system.

lcobucci commented 4 years ago

@Saawaabaa hello there and welcome to the awesome world of routing systems :wave:

This library focus on giving you a way to find the correct handler, it's up to you to define how you "parse" the handler information.

Perhaps using an array as the handler might make your life simpler:

$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/users', [Users::class, 'listAll']);
});

// Then you'll do:

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);

if ($routeInfo[0] === FastRoute\Dispatcher::FOUND) {
    [$className, $method] = $routeInfo[1];

    // Instantiate `$className` or use fetch an object via your DI container and call the method `$method`
}
lcobucci commented 4 years ago

Will be closing for now, please re-open if you need more information :+1: