All the routes for your application would live in the Routes folder. Mighty will scan through the entire Routes folder and pick up all .php
files within in. Therefore, you are able to create as many separate files as you like to organize your routes.
For example:
- Routes- user.php- auth.php- admin.php- home.php
Where each of the files will correspond to its own routes. user.php
may contain routes to all user related endpoints, while admin.php
will contain all that is admin related.
Mighty's router work in scopes. A scope is a group of routes, with or without a prefix. To declare a scope, simply create a new Router()
object.
<?phpuse MightyCore\Routing\Router;​// Notice that '/' means root path$router = new Router('/');
Now you have created a new scope which has no prefix. You can then add your routes as such:
<?phpuse MightyCore\Routing\Router;​$router = new Router('/');​// URL is example.com$router->get('/', '[email protected]');​// URL is example.com/login$router->get('/login', '[email protected]');​// URL is example.com/user/add$router->get('/user/add', '[email protected]');
Let's make things nicer. Although the routing above will work, but as your application increases in size, more and more routes will come in, and each may want to implement its own middlewares or naming. It will pretty soon grow out of hand.
Let's try to refactor the /user
paths into a new scope:
<?phpuse MightyCore\Routing\Router;​$router = new Router('/');// URL is example.com$router->get('/', '[email protected]');// URL is example.com/login$router->get('/login', '[email protected]');​​// Create a new scope$userRouter = new Router('/user');// URL is example.com/user/add$userRouter->get('/add', '[email protected]');
This way, we can better organize our routes as they are self contained within their scopes and prefixes.
To organize further, we can refactor the codes into separate route files:
Routes/home.php<?phpuse MightyCore\Routing\Router;​$router = new Router('/');// URL is example.com$router->get('/', '[email protected]');// URL is example.com/login$router->get('/login', '[email protected]');
Routes/user.php<?phpuse MightyCore\Routing\Router;​// Create a new scope$userRouter = new Router('/user');// URL is example.com/user/add$userRouter->get('/add', '[email protected]');