Routing in Hazaar
Routing in Hazaar
Hazaar provides a robust and flexible routing system that allows you to map URLs to controllers and actions in your application. The framework supports multiple routing methods, each designed to suit different application requirements and developer preferences. Whether you need simple automatic routing or advanced, highly configurable routes, Hazaar has you covered.
Routing is a core feature of Hazaar, enabling clean, intuitive URLs and powerful request handling. You can configure routing in your app using a variety of methods, including PHP files, JSON files, controller attributes, and more. Each method offers unique advantages and is suitable for different scenarios.
File Router Example
This example focuses on the file router, which is ideal for routes not directly tied to a controller and for programmatic route definition.
routes.php
Define routes in a routes.php file using the Hazaar\Application\Router helper. You can use closures, controller methods, or class strings as callables.
<?php
use Hazaar\Application\Router;
use Hazaar\Controller\Response\View;
use App\Controller\Index;
use App\Controller\API;
Router::get('/', [Index::class, 'index']);
Router::get('/about', function() {
return View('about');
});
Router::get('/api/v1/product', [API::class, 'listProducts']);
Router::post('/api/v1/product', [API::class, 'createProduct']);Configuration (app.php)
Enable the file router in app.php and point it at your route file. The file router is the default router, and routes.php is the default source file, but both are entirely configurable. Router configuration lives under an environment key so you can define different route sets per environment.
return [
'development' => [
'router' => [
'type' => 'file',
'file' => 'routes.php'
]
]
];Other Routing Methods
Hazaar supports several routing methods. These documents live in the basics routing section: