Repository navigation
URL Converters
SyFramework can expose the same application through two URL styles:
| Style | Example |
|---|---|
| Query string | /index.php?p=page&a=article&id=42 |
| Clean URL |
/a/hello-world, /fr/page/foo/hello-world, /u/123
|
URL converters translate a clean path into the request parameters used by the framework, and translate parameters back into a URL. They live in Sy\Bootstrap\Lib\Url and implement Sy\Bootstrap\Lib\Url\IConverter.
Converters are optional. When URL rewriting is disabled, the application keeps working with p / a query parameters only.
Browser
│
▼
.htaccess rewrite non-file/non-directory requests to index.php
│
▼
index.php load configuration + Composer autoload
│
▼
Project\Application extends Sy\Bootstrap\Application
│
├─ URL_REWRITING enabled?
│ ├─ initUrlConverter() register converters, in priority order
│ └─ Url::analyse() parse REQUEST_URI and fill $_GET / $_REQUEST
│
└─ read CONTROLLER_TRIGGER select the controller class
│
▼
Controller / Page
Relevant code:
-
project/.htaccessrewrites everything that is not an existing file or directory toindex.php. -
URL_REWRITINGis defined inproject/protected/conf/conf.php. -
Sy\Bootstrap\Application::init()callsinitUrlConverter()andUrl::analyse()only whenURL_REWRITINGis truthy. -
Project\ApplicationoverridesinitUrlConverter()to register the application converters. -
Url::analyse()callsconvertToParams($_SERVER['REQUEST_URI'])and copies the result into both$_REQUESTand$_GET.
Because Url::analyse() runs before language detection, a converter can set lang (and even change the current language) before the lang service resolves the display language.
All built-in converters compare the request path with WEB_ROOT. WEB_ROOT must contain the public path prefix of the application:
define('WEB_ROOT', ''); // application at the domain root
// define('WEB_ROOT', '/myapp'); // application in a subdirectoryConverters generally do:
$path = trim(substr($uri, strlen(WEB_ROOT) + 1), '/');This assumes that the URL starts with WEB_ROOT followed by /. A mismatch produces empty or truncated paths.
Converters produce the same parameters as a query-string URL:
| Constant | Query parameter | Role |
|---|---|---|
CONTROLLER_TRIGGER |
p |
Controller name (page, api, editor, sitemap, ...) |
ACTION_TRIGGER |
a |
Action name; also the page id for the page controller |
ACTION_PARAM |
a_param |
Ordered action parameters |
lang |
lang |
Language code |
For example, the URL:
/fr/page/foo/hello-world?view=full
is analysed as:
$_GET = [
'p' => 'page',
'a' => 'foo',
'a_param' => ['hello-world'],
'lang' => 'fr',
'view' => 'full',
];For p=page, Application\Page uses a as the page id, then dispatches <a>Action():
$pageId = $this->get(ACTION_TRIGGER, 'home');
$this->actionDispatch(ACTION_TRIGGER);ACTION_PARAM is not dispatched by the page controller. It remains available in $_GET / $_REQUEST, and it is used by the API layer (Sy\Bootstrap\Component\Api) to select an action method.
namespace Sy\Bootstrap\Lib\Url;
interface IConverter {
/**
* @param array $params
* @return string|false
*/
public function paramsToUrl(array $params);
/**
* @param string $url
* @return array|false
*/
public function urlToParams($url);
}Rules:
- Return
falsewhen the converter is not responsible for the URL or the parameters. - Return an array from
urlToParams()when the URL matches. - Return a string from
paramsToUrl()when the parameters match. - Converters are evaluated in registration order. The first non-
falseresult wins; there is no backtracking. - A converter must not throw for a normal "not my URL" case. Exceptions are not handled by
Url. -
urlToParams()receives the full request URI, includingWEB_ROOTand the query string. Useparse_url()to split path and query. -
paramsToUrl()receives the full parameter array, including unknown query parameters. It should consume only the keys it understands and append the rest withhttp_build_query().
The reference shape is:
public function urlToParams($url) {
$uri = parse_url($url, PHP_URL_PATH);
$queryString = parse_url($url, PHP_URL_QUERY);
// ... match $uri ...
$queryParams = [];
if (!is_null($queryString)) parse_str($queryString, $queryParams);
return $params + $queryParams;
}$params + $queryParams means converter-produced parameters win over query-string parameters with the same key.
Converters are registered from Project\Application::initUrlConverter():
<?php
namespace Project;
use Sy\Bootstrap\Lib\Url;
class Application extends \Sy\Bootstrap\Application {
protected function initUrlConverter() {
Url\AliasManager::setAliasFile(__DIR__ . '/../conf/alias.php');
Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ControllerActionConverter());
}
}Url::addConverter() appends to a static list. The order of the addConverter() calls is the priority order. In practice, the last converter in the list is the fallback, provided it is terminal (it matches everything); the standard configuration uses ControllerActionConverter for that role.
Recommended ordering:
-
Specific converters first — converters with a fixed prefix or a narrow match (
ItemIdConverter,ArticleConverter).ContentConverteris less specific because its default prefix is empty; place it after the prefixed converters. -
AliasConverterwhere aliases should sit in the precedence — before specific converters if aliases must win, after them if prefixed URLs must win. -
ControllerActionConverterlast — it is the terminal fallback.
ControllerActionConverter matches any non-empty path. It therefore acts as a fallback by convention. Nothing in the code declares it as a fallback: a converter registered after it would never be reached.
Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ControllerActionConverter());Aliases are checked first, then every other path becomes /controller/action.
Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ArticleConverter());
Url::addConverter(new Url\ControllerActionConverter());Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ContentConverter());
Url::addConverter(new Url\ControllerActionConverter());A real application can combine several prefix converters and place aliases after them:
Url::addConverter(new Url\ItemIdConverter('user', 'u'));
Url::addConverter(new Url\ArticleConverter());
Url::addConverter(new Url\ItemIdConverter('lists', 'l'));
Url::addConverter(new Url\ItemIdConverter('review', 'r'));
Url::addConverter(new Url\ItemIdConverter('message', 'm'));
Url::addConverter(new Url\ItemIdConverter('vote', 'v'));
Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ControllerActionConverter());Here /u/123 is always handled by ItemIdConverter, even if an alias u/123 exists. The position of AliasConverter is the policy decision.
Static aliases loaded from project/protected/conf/alias.php.
<?php
return [
'fr' => [
'accueil' => 'page/home',
'articles/categorie-1' => 'page/articles?category=1',
],
'en' => [
'home' => 'page/home',
],
];-
urlToParams()performs an exact alias match, then setslangfrom the alias language and merges the query string. -
paramsToUrl()rebuildscontrollerorcontroller/action, looks up the alias for the requested language, and appends unused parameters. - An alias target is limited to
controllerorcontroller/action, with an optional query string. It cannot targetACTION_PARAM. - If an exact alias including the query string exists, that alias is used and the query string is not appended again. Otherwise the path-only alias is used and the query string is appended.
Example:
/accueil
⇔ p=page, a=home, lang=fr
/articles/categorie-1
⇔ p=page, a=articles, category=1, lang=fr
The default human-readable form:
/[lang]/<controller>/<action>/<param1>/<param2>?<query>
Examples:
/fr/page/foo/hello-world?view=full
⇔ p=page, a=foo, a_param=[hello-world], lang=fr, view=full
/page/articles
⇔ p=page, a=articles
- A first path segment listed in
LANGSis consumed aslang. - The next segment is the controller; the next is the action; all remaining segments become
ACTION_PARAM. -
paramsToUrl()accepts either an array forACTION_PARAMor an action string containing slashes ('foo/bar/baz'). - It returns
falsefor an empty path or root URL. - It matches any other non-empty path, so it must be registered last.
Maps a page action to a short identifier route:
/[lang]/<urlId>/<id>
⇔ p=page, a=<pageId>, id=<id>
Constructor:
new Url\ItemIdConverter($pageId, $urlId = '');$urlId defaults to $pageId.
Examples:
new Url\ItemIdConverter('user', 'u');
// /u/123 ⇔ p=page, a=user, id=123
new Url\ItemIdConverter('lists', 'l');
// /l/123 ⇔ p=page, a=lists, id=123-
paramsToUrl()requiresp=page,a=<pageId>and a non-emptyid. -
urlToParams()extracts the value after<urlId>/and returns it asid. - The id is exposed in the URL. Use this converter for stable numeric identifiers, not for content that needs opaque or SEO-friendly URLs.
- There is no numeric validation: the value is whatever follows the prefix.
-
$urlIddefaults to$pageId. A converter built with an empty page id has no usable prefix and does not match.
Plugins and applications add converters by implementing IConverter and registering them in initUrlConverter().
/a/<alias>
⇔ p=page, a=article, id=<id>, lang=<article lang>
- Prefix defaults to
a/; it can be changed through the constructor. -
paramsToUrl()usesaliaswhen provided; otherwise it retrieves the article byidand the requested language (default: current language) to obtain the alias. -
urlToParams()retrieves the article by alias, then returnsp=page,a=article,idandlang. - It also calls
$service->user->setLanguage($article['lang']). This is intentional: an article URL has no language segment, so the article language becomes the display language for the request and is persisted in the session / cookie by the language service. - Article aliases are unique in the
t_articletable.
Example:
/a/hello-world
⇔ p=page, a=article, id=42, lang=fr
/[lang]/<alias>
⇔ p=page, a=content, id=<id>
- Prefix defaults to an empty string, so content URLs live at the site root.
-
paramsToUrl()usesaliaswhen provided; otherwise it retrieves the content byid. - An empty alias produces the site root (
WEB_ROOT, orWEB_ROOT/<lang>when a language is provided). -
urlToParams()consumes an optional language prefix, then retrieves the content by alias. - It does not change the current language; the language comes from the optional path prefix or from the normal language detection.
- Because the default prefix is empty, this converter checks every unknown root path against the content table. Register it before
ControllerActionConverter, but after more specific converters.
Examples:
/hello-world
⇔ p=page, a=content, id=7
/en/hello-world
⇔ p=page, a=content, id=7, lang=en
The framework itself does not ship every possible converter. Applications and external packages provide their own, for example:
-
sybootstrapprovidesPlaceConverter,ListConverterandUserConverter; - applications may add
ItemIdConverterinstances for reviews, messages, votes, etc.
Url::build() is the reverse entry point:
Url::build($controller, $action = null, array $parameters = [], $anchor = null);It builds a parameter array, asks every converter for a URL, and falls back to a query-string URL when no converter matches.
Url::build('page', 'article', ['id' => 42]);
// With AliasConverter + ArticleConverter + ControllerActionConverter:
// /a/hello-world (if the article has an alias)
Url::build('page', 'articles', ['category' => 1]);
// /fr/page/articles?category=1
Url::build('api', 'page', ['id' => 'home', 'lang' => 'fr']);
// /fr/api/page?id=home
Url::build('api', ['content', 'valid']);
// /api/content/validThe last example is important: when ControllerActionConverter is registered, an action array is rendered as path segments (/api/content/valid), not as ?p=api&a=content&a_param[0]=valid. The query form is the fallback used when no converter matches, typically when URL rewriting is disabled.
Behaviour details:
- For
page,Url::build()adds the current language whenlangis absent. -
ControllerActionConverterconsumes a validlangparameter as a path prefix for any controller, not onlypage. That is why an explicitlangpassed forapiproduces/fr/api/...instead of alang=query parameter. -
$params + $parametersis passed to the converters: converter keys (p,a) win over parameters with the same name. - If a converter returns a URL, the anchor is appended.
- If no converter matches, the fallback is
$_SERVER['PHP_SELF']plus a query string. An array action becomesaplusa_param[0..n]. - Absolute URLs are usually built by prefixing with
PROJECT_URL:
$url = PROJECT_URL . Url::build('page', 'article', ['id' => 42]);| URL | Parameters after Url::analyse()
|
|---|---|
/fr/page/foo/hello-world?view=full |
p=page, a=foo, a_param=[hello-world], lang=fr, view=full
|
/a/hello-world |
p=page, a=article, id=42, lang=fr
|
/en/hello-world |
p=page, a=content, id=7, lang=en
|
/u/123 |
p=page, a=user, id=123
|
/accueil |
p=page, a=home, lang=fr
|
/index.php?p=page&a=article&id=42 |
query-string mode; no converter involved |
-
.htaccessforwards the request toindex.php. -
Project\Application::initUrlConverter()registers the converters. -
Url::analyse()asks each converter in order. -
AliasConverterreturnsfalse;ArticleConvertermatches and loads the article by alias. -
ArticleConvertersetsp=page,a=article,id=42,lang=fr, and changes the current language. -
Url::analyse()copies those values into$_GET/$_REQUEST. -
Applicationreadsp=pageand instantiates the page controller. -
Application\Pageusesa=articleas the page id and callsarticleAction(). -
articleAction()readsidand renders the article.
Minimal prefix converter:
<?php
namespace Project\Lib\Url;
use Sy\Bootstrap\Lib\Url\IConverter;
class ProductConverter implements IConverter {
private $prefix;
public function __construct($prefix = 'p/') {
$this->prefix = $prefix;
}
public function paramsToUrl(array $params) {
if (empty($params[CONTROLLER_TRIGGER])) return false;
if ($params[CONTROLLER_TRIGGER] !== 'page') return false;
unset($params[CONTROLLER_TRIGGER]);
if (empty($params[ACTION_TRIGGER])) return false;
if ($params[ACTION_TRIGGER] !== 'product') return false;
unset($params[ACTION_TRIGGER]);
if (empty($params['slug'])) return false;
$slug = $params['slug'];
unset($params['slug']);
return WEB_ROOT . '/' . $this->prefix . $slug . (empty($params) ? '' : '?' . http_build_query($params));
}
public function urlToParams($url) {
$uri = parse_url($url, PHP_URL_PATH);
$queryString = parse_url($url, PHP_URL_QUERY);
$path = trim(substr($uri, strlen(WEB_ROOT) + 1), '/');
list($slug) = sscanf($path, $this->prefix . '%s');
if (empty($slug)) return false;
$product = \Project\Service\Container::getInstance()->product->retrieve(['slug' => $slug]);
if (empty($product)) return false;
$params = [
CONTROLLER_TRIGGER => 'page',
ACTION_TRIGGER => 'product',
'id' => $product['id'],
];
$queryParams = [];
if (!is_null($queryString)) parse_str($queryString, $queryParams);
return $params + $queryParams;
}
}Register it before ControllerActionConverter:
Url::addConverter(new \Project\Lib\Url\ProductConverter());
Url::addConverter(new Url\ControllerActionConverter());Checklist for a new converter:
- It returns
falsefor URLs / parameters it does not own. - It consumes only its own keys and appends the remaining parameters.
- It handles
WEB_ROOTand the query string. - It is registered before
ControllerActionConverter. - Its position relative to
AliasConverteris intentional. - It has tests for both directions:
urlToParams()andparamsToUrl().
-
Ordering is implicit.
addConverter()order is the only priority mechanism. There is no priority argument, duplicate detection, reachability check, or introspection API. -
The fallback is a convention.
ControllerActionConverteris terminal because it matches any non-empty path, not because the code marks it as a fallback. A converter registered after it is unreachable. -
The registry is static.
Url::$convertershas no reset or remove method. Tests must isolate it explicitly. -
AliasConverteris static and manual.- Aliases must be maintained by hand in
alias.php. - Matching is exact; there are no parameterized aliases.
- Targets are limited to
controllerorcontroller/actionplus a query string. - If the same alias exists in several languages, the first language in the file wins.
- If several aliases map to the same path,
retrieveAlias()returns the first one. - A missing or invalid alias file is silently ignored.
- Aliases must be maintained by hand in
- Alias resolution is only partially normalized. Leading and trailing slashes are trimmed from the alias, but internal duplicate slashes and query parameter order are not normalized before lookup.
-
Domain converters query the database during URL analysis and generation.
-
ArticleConverter::paramsToUrl()retrieves the article when onlyidis provided. -
ContentConverterchecks every unknown root path againstt_content. - There is no cache in the converters themselves.
-
-
ArticleConverterchanges the current language.urlToParams()callsuser->setLanguage($article['lang']); this is intentional for language-less article URLs, but it persists in the session / cookie. -
ItemIdConverterexposes identifiers. IDs are enumerable, not opaque. The converter also performs no numeric validation, and%saccepts slashes and arbitrary characters after the prefix. -
Path segments are not decoded or normalized.
parse_url()does not decode percent-encoded segments; an encoded slug may not match a database alias. Trailing-slash handling is inconsistent between converters. -
A language segment can shadow a controller.
ControllerActionConverter,ItemIdConverterandContentConvertertreat the first segment aslangwhenever it is listed inLANGS; a controller with the same name cannot be reached through the clean URL. -
Url::analyse()overwrites request data. Converter output replaces existing$_GETand$_REQUESTvalues with the same keys. Built-in converters return$params + $queryParams, so converter parameters win over query-string parameters. -
falsemeans "not mine", not "invalid". A malformed URL can fall through toControllerActionConverterand be interpreted as an unknown controller/action instead of producing a routing error. -
Url::build()fallback is rarely used. WithControllerActionConverterregistered, almost every parameter set produces a path URL.$_SERVER['PHP_SELF']is used for the remaining cases. -
Url::build()only addslangautomatically forpage. Other controllers must passlangexplicitly when the URL should carry it. -
Test coverage is partial.
AliasConverter,ControllerActionConverter,ItemIdConverterandContentConverterhave unit tests.ArticleConverterdoes not, and there is no integration test for converter ordering.
These are not part of the current contract; they are candidates for a future change.
-
Explicit fallback / priority API. Add a way to mark the fallback converter (for example
Url::setFallbackConverter()), or giveaddConverter()an optional priority while preserving insertion order by default. - Reachability diagnostics. Detect converters registered after a terminal converter and report them in development.
- Introspection and debug trace. Expose the converter list and log which converter matched a request.
-
Indexed aliases. Build
alias => [path, lang]andlang|path|query => aliasindexes at load time instead of scanning arrays. - Alias validation. Detect duplicate aliases, duplicate paths, and aliases declared in several languages; define an explicit language precedence (current language, default language, declaration order).
- Normalization. Normalize trailing slashes and query parameter order before alias lookup.
- Caching. Cache database lookups performed by domain converters.
- Path decoding. Decode path segments consistently before matching.
-
More tests. Add
ArticleConvertertests and integration tests covering converter order and alias collisions.