Skip to content

Commit 33c59bf

Browse files
authored
Merge pull request #5 from dicoding-dev/feature/invokable-controller
Implements single action controller
2 parents 84b6c7d + a331c2e commit 33c59bf

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/Illuminate/Routing/Router.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -992,9 +992,13 @@ protected function getClassClosure($controller)
992992
// Now we can split the controller and method out of the action string so that we
993993
// can call them appropriately on the class. This controller and method are in
994994
// in the Class@method format and we need to explode them out then use them.
995-
[$class, $method] = explode('@', $controller);
995+
$controller = explode('@', $controller);
996+
$class = $controller[0];
996997

997-
return $d->dispatch($route, $request, $class, $method);
998+
// if route action doesn't define method, then by default use `__invoke` method, thus invokable action
999+
$method = $controller[1] ?? '__invoke';
1000+
1001+
return $d->dispatch($route, $request, $class, $method);
9981002
};
9991003
}
10001004

tests/Routing/RoutingRouteTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,21 @@ public function testRouteRedirect()
898898
}
899899

900900

901+
public function testDispatchingCallableActionClasses()
902+
{
903+
$router = $this->getRouter();
904+
$router->get('foo/bar', 'ActionStub');
905+
906+
$this->assertEquals('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
907+
908+
$router->get('foo/bar2', [
909+
'uses' => 'ActionStub',
910+
]);
911+
912+
$this->assertEquals('hello', $router->dispatch(Request::create('foo/bar2', 'GET'))->getContent());
913+
}
914+
915+
901916
protected function getRouter(): Router
902917
{
903918
return new Router(new Illuminate\Events\Dispatcher);
@@ -994,3 +1009,11 @@ public function handle(): string
9941009
return 'handling!';
9951010
}
9961011
}
1012+
1013+
class ActionStub extends Controller
1014+
{
1015+
public function __invoke(): string
1016+
{
1017+
return 'hello';
1018+
}
1019+
}

0 commit comments

Comments
 (0)