Implicit route controllers

Learn how to create implicit routes within a controller's methods to create paths using HTTP methods.

Create controller

The method names represent the HTTP methods and paths required by the routes, for example:

Method Route method Route path Equivalent
getInfo() GET /info $app->action('GET', '/info')
putInfo() PUT /info $app->action('PUT', '/info')
putfooBar() PUT /foo-bar $app->action('PUT', '/foo-bar')
postPing() POST /ping $app->action('POST', '/ping')
anyFooBarBaz() ANY /foo-bar-baz $app->action('ANY', '/foo-bar-baz')
getIndex() GET / $app->action('GET', '/')
headIndex() HEAD / $app->action('HEAD', '/')
deleteSomething() DELETE /something $app->action('DELETE', '/something')

To test, create the file system/Controllers/ImplicitController.php and then add the following content to it:

<?php namespace Controller; class ImplicitController extends \Inphinit\Routing\Treaty { public function getIndex() { return 'Home'; } public function getInfo() { phpinfo(); } public function postPing() { error_log($_SERVER['REMOTE_ADDR']); } public function anyFooBarBaz() { phpinfo(); } }

Then add this to main.php or dev.php:

\Controller\ImplicitController::action($app);

Is equivant to:

$app->action('GET', '/', 'ImplicitController::getIndex'); $app->action('GET', '/info', 'ImplicitController::getInfo'); $app->action('POST', '/ping', 'ImplicitController::postPing'); $app->action('ANY', '/foo-bar-baz', 'ImplicitController::anyFooBarBaz');

Limitations

The difference with controllers that implicitly create routes is that only ANY or one HTTP method can be used per route, whereas in normal route declarations it is possible to add more than one HTTP method. The following example cannot be written in the form of a controller that implicitly creates routes:

$app->action(['GET', 'HEAD'], '/', 'FooBar::home'); $app->action(['POST', 'PUT', 'PATCH'], '/test', 'FooBar::test');

In routes implicitly created to have different methods for the same path, it will always be necessary to create a class method for each method of a path, thus resulting in different routes:

<?php namespace Controller; class FooBar extends \Inphinit\Routing\Treaty { public function getIndex() { ... } public function headIndex() { ... } public function postTest() { ... } public function putTest() { ... } public function patchTest() { ... } }
Go to homepage
Star us on Github