Basic Router
Basic Router
The basic router uses the request URL to determine the controller and action, along with any arguments. No configuration is required, as controllers and actions are automatically mapped to URLs.
This router is the simplest and fastest way to perform routing in Hazaar as there is minimal processing required. However, it is limited in its ability to handle complex routing scenarios such as nested controllers, custom routes, or route aliases.
Tips
The basic router is ideal for simple applications with a flat controller structure that require the most efficient routing possible.
URL Structure
A typical route format is:
/controller/action/arg1/arg2/argxExample:
/product/get/1234This URL loads the Application\Controller\Product controller and executes its get method with 1234 as an argument.
Example Controller
namespace App\Controller;
use Hazaar\Controller\Basic;
use Hazaar\Controller\Response\Json;
use Hazaar\DBI\Adapter;
class Product extends Basic {
public function init(): void
{
// Initialization code
}
public function get(int $productId): Json
{
$db = Adapter::create();
return new Json($db->table('product')->find(['id' => $productId]));
}
}Automatic Type Conversion
When arguments are passed to a controller method from the URL, Hazaar performs automatic type conversion based on the method's parameter type hints. This ensures that your controller receives data in the expected format without requiring manual casting.
If a parameter has no type hint, the value is passed as a string.
Supported Conversions:
- int: Converts numeric strings to integers.
- float: Converts numeric strings to floats.
- bool: Converts strings like "true", "1", "yes", "on" to
true, and others tofalse. - string: Passes the value as is (default).
Example:
Request URL: /product/update/1234/true
Controller Method:
public function update(int $productId, bool $enableFn): Json
{
// $productId is (int) 1234
// $enableFn is (bool) true
return new Json(['status' => 'OK']);
}Configuration (app.php)
<?php
return [
'development' => [
'router' => [
'type' => 'basic',
'controller' => 'product',
'action' => 'get'
]
]
];