Skip to content

URL Converters

Syone edited this page Nov 19, 2026 · 1 revision

Overview

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.

Request pipeline

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/.htaccess rewrites everything that is not an existing file or directory to index.php.
  • URL_REWRITING is defined in project/protected/conf/conf.php.
  • Sy\Bootstrap\Application::init() calls initUrlConverter() and Url::analyse() only when URL_REWRITING is truthy.
  • Project\Application overrides initUrlConverter() to register the application converters.
  • Url::analyse() calls convertToParams($_SERVER['REQUEST_URI']) and copies the result into both $_REQUEST and $_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.

WEB_ROOT

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 subdirectory

Converters 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.

Parameter model

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.

The IConverter contract

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 false when 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-false result 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, including WEB_ROOT and the query string. Use parse_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 with http_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.

Registration and ordering

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:

  1. Specific converters first — converters with a fixed prefix or a narrow match (ItemIdConverter, ArticleConverter). ContentConverter is less specific because its default prefix is empty; place it after the prefixed converters.
  2. AliasConverter where aliases should sit in the precedence — before specific converters if aliases must win, after them if prefixed URLs must win.
  3. ControllerActionConverter last — 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.

Default project

Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ControllerActionConverter());

Aliases are checked first, then every other path becomes /controller/action.

Article plugin

Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ArticleConverter());
Url::addConverter(new Url\ControllerActionConverter());

CMS plugin

Url::addConverter(new Url\AliasConverter());
Url::addConverter(new Url\ContentConverter());
Url::addConverter(new Url\ControllerActionConverter());

Application with identifier routes

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.

Built-in converters

AliasConverter

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 sets lang from the alias language and merges the query string.
  • paramsToUrl() rebuilds controller or controller/action, looks up the alias for the requested language, and appends unused parameters.
  • An alias target is limited to controller or controller/action, with an optional query string. It cannot target ACTION_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

ControllerActionConverter

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 LANGS is consumed as lang.
  • The next segment is the controller; the next is the action; all remaining segments become ACTION_PARAM.
  • paramsToUrl() accepts either an array for ACTION_PARAM or an action string containing slashes ('foo/bar/baz').
  • It returns false for an empty path or root URL.
  • It matches any other non-empty path, so it must be registered last.

ItemIdConverter

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() requires p=page, a=<pageId> and a non-empty id.
  • urlToParams() extracts the value after <urlId>/ and returns it as id.
  • 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.
  • $urlId defaults to $pageId. A converter built with an empty page id has no usable prefix and does not match.

Plugin and application converters

Plugins and applications add converters by implementing IConverter and registering them in initUrlConverter().

ArticleConverter (sy/bootstrap-article)

/a/<alias>
  ⇔ p=page, a=article, id=<id>, lang=<article lang>
  • Prefix defaults to a/; it can be changed through the constructor.
  • paramsToUrl() uses alias when provided; otherwise it retrieves the article by id and the requested language (default: current language) to obtain the alias.
  • urlToParams() retrieves the article by alias, then returns p=page, a=article, id and lang.
  • 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_article table.

Example:

/a/hello-world
  ⇔ p=page, a=article, id=42, lang=fr

ContentConverter (sy/bootstrap-cms)

/[lang]/<alias>
  ⇔ p=page, a=content, id=<id>
  • Prefix defaults to an empty string, so content URLs live at the site root.
  • paramsToUrl() uses alias when provided; otherwise it retrieves the content by id.
  • An empty alias produces the site root (WEB_ROOT, or WEB_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

External converters

The framework itself does not ship every possible converter. Applications and external packages provide their own, for example:

  • sybootstrap provides PlaceConverter, ListConverter and UserConverter;
  • applications may add ItemIdConverter instances for reviews, messages, votes, etc.

Building URLs with Url::build()

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/valid

The 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 when lang is absent.
  • ControllerActionConverter consumes a valid lang parameter as a path prefix for any controller, not only page. That is why an explicit lang passed for api produces /fr/api/... instead of a lang= query parameter.
  • $params + $parameters is 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 becomes a plus a_param[0..n].
  • Absolute URLs are usually built by prefixing with PROJECT_URL:
$url = PROJECT_URL . Url::build('page', 'article', ['id' => 42]);

End-to-end examples

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

Walkthrough: /a/hello-world

  1. .htaccess forwards the request to index.php.
  2. Project\Application::initUrlConverter() registers the converters.
  3. Url::analyse() asks each converter in order.
  4. AliasConverter returns false; ArticleConverter matches and loads the article by alias.
  5. ArticleConverter sets p=page, a=article, id=42, lang=fr, and changes the current language.
  6. Url::analyse() copies those values into $_GET / $_REQUEST.
  7. Application reads p=page and instantiates the page controller.
  8. Application\Page uses a=article as the page id and calls articleAction().
  9. articleAction() reads id and renders the article.

Writing a custom converter

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 false for URLs / parameters it does not own.
  • It consumes only its own keys and appends the remaining parameters.
  • It handles WEB_ROOT and the query string.
  • It is registered before ControllerActionConverter.
  • Its position relative to AliasConverter is intentional.
  • It has tests for both directions: urlToParams() and paramsToUrl().

Known limitations

  • 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. ControllerActionConverter is 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::$converters has no reset or remove method. Tests must isolate it explicitly.
  • AliasConverter is static and manual.
    • Aliases must be maintained by hand in alias.php.
    • Matching is exact; there are no parameterized aliases.
    • Targets are limited to controller or controller/action plus 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.
  • 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 only id is provided.
    • ContentConverter checks every unknown root path against t_content.
    • There is no cache in the converters themselves.
  • ArticleConverter changes the current language. urlToParams() calls user->setLanguage($article['lang']); this is intentional for language-less article URLs, but it persists in the session / cookie.
  • ItemIdConverter exposes identifiers. IDs are enumerable, not opaque. The converter also performs no numeric validation, and %s accepts 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, ItemIdConverter and ContentConverter treat the first segment as lang whenever it is listed in LANGS; a controller with the same name cannot be reached through the clean URL.
  • Url::analyse() overwrites request data. Converter output replaces existing $_GET and $_REQUEST values with the same keys. Built-in converters return $params + $queryParams, so converter parameters win over query-string parameters.
  • false means "not mine", not "invalid". A malformed URL can fall through to ControllerActionConverter and be interpreted as an unknown controller/action instead of producing a routing error.
  • Url::build() fallback is rarely used. With ControllerActionConverter registered, almost every parameter set produces a path URL. $_SERVER['PHP_SELF'] is used for the remaining cases.
  • Url::build() only adds lang automatically for page. Other controllers must pass lang explicitly when the URL should carry it.
  • Test coverage is partial. AliasConverter, ControllerActionConverter, ItemIdConverter and ContentConverter have unit tests. ArticleConverter does not, and there is no integration test for converter ordering.

Possible improvements

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 give addConverter() 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] and lang|path|query => alias indexes 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 ArticleConverter tests and integration tests covering converter order and alias collisions.

See also

  • Form — form component and submission flow.
  • API — API routing, responses and security.

Clone this wiki locally