Generating URLs
Generating URLs
Generating URLs in Hazaar is done using the Hazaar\Application\URL class. This class is designed to easily construct URLs that are relative to your application's base path, ensuring portability across different environments (e.g., localhost vs production).
Hazaar\Application\URL extends the powerful Hazaar\HTTP\URL class, inheriting a wide range of methods for parsing, modifying, and rendering URLs.
Basic Usage
To generate a URL, simply instantiate the Hazaar\Application\URL class. The constructor calculates the base URL of your application automatically.
use Hazaar\Application\URL;
$url = new URL();
echo $url; // Outputs: http://localhost/ (or your app's base path)Constructing Paths
The constructor accepts a variable number of arguments which are joined to form the path relative to the application root.
// http://localhost/controller
$url = new URL('controller');
// http://localhost/controller/action
$url = new URL('controller', 'action');
// You can also use forward slashes in strings
// http://localhost/media/images/logo.png
$url = new URL('media/images', 'logo.png');Adding Query Parameters
Query parameters can be added in a few ways:
- Passing an associative array as an argument to the constructor (or an object).
- Including them in a path string (they will be parsed automatically).
- Using generic methods from
Hazaar\HTTP\URL.
Constructor Arguments
When passing parameters as an array, it should be the last argument, as processing stops after the parameter array is found.
// http://localhost/controller/action?id=123
$url = new URL('controller', 'action', ['id' => 123]);
// http://localhost/search?q=hazaar&p=1
$url = new URL('search', ['q' => 'hazaar', 'p' => 1]);In Path Strings
// http://localhost/controller/action?type=list
$url = new URL('controller/action?type=list');Hazaar\HTTP\URL Features
Since Hazaar\Application\URL extends Hazaar\HTTP\URL, you have full access to the underlying URL manipulation components.
Path and Query Manipulation
$url = new URL('api');
$url->appendPath('v1/users');
$url->set('format', 'json');
echo $url;
// Output: http://localhost/api/v1/users?format=jsonAccessing Components
You can read or write individual components of the URL.
$url = new URL('login');
// Check or force scheme
if (!$url->isSecure()) {
$url->scheme('https');
}
// Set hash fragment
$url->hash('top');
// Get parameters
$params = $url->params();Magic Methods
The class implements __toString() for easy output, and __get()/__set() for property access.
$url = new URL('home');
echo '<a href="' . $url . '">Home</a>';