Skip to content
PHP Ecosystem
Explore

UrlLanguageManager

API reference › Locale URLs › UrlLanguageManager

classyii2\extensions\localeurls\UrlLanguageManager
Extendsyii\web\UrlManager » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Sourcesrc/UrlLanguageManager.php

Resolves the application language from a URL code, the persisted choice, the browser, or GeoIP, and adds the language code to created URLs.

A URL without a code redirects to the persisted or detected language; a URL with the default language code redirects to the URL without it unless $enableDefaultLanguageUrlCode is true.

The manager keeps no per-request state and is safe for long-running workers; redirects are raised as UrlNormalizerRedirectException and handled by the application.

See also: LanguageChangedEvent.

PropertyTypeDescriptionDefined by
$baseUrlstringThe base URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$cacheyii\caching\CacheInterface|array|string|bool|nullThe cache object or the application component ID of the cache object. Default: 'cache'.yii\web\UrlManager
$defaultLanguagestring|nullDefault language: the language of URLs without a code when $enableDefaultLanguageUrlCode is false. Default: null.UrlLanguageManager
$enableDefaultLanguageUrlCodeboolWhether the default language uses a URL code like any other language. Default: false.UrlLanguageManager
$enableLanguageDetectionboolWhether to detect the language from the Accept-Language header when the URL has no code and no language is persisted. Default: true.UrlLanguageManager
$enableLanguagePersistenceboolWhether to persist the language from the URL in the session and the language cookie. Default: true.UrlLanguageManager
$enableLocaleUrlsboolWhether to enable language processing; when false, the manager behaves like UrlManager. Default: true.UrlLanguageManager
$enablePrettyUrlWhether to enable pretty URLs; must be true while locale URLs are enabled. Default: true.UrlLanguageManager
$enableStrictParsingboolWhether to enable strict parsing. Default: false.yii\web\UrlManager
$geoIpLanguageCountriesarrayGeoIP country codes indexed by the language they select. Default: [].UrlLanguageManager
$geoIpServerVarstringName of the server variable that carries the GeoIP country code. Default: 'HTTP_X_GEO_COUNTRY'.UrlLanguageManager
$hostInfostringThe host info (e.g. https://www.example.com) that is used by createAbsoluteUrl() to prepend to created URLs.yii\web\UrlManager
$ignoreLanguageUrlPatternsarrayRegular expressions that exclude routes and URLs from language processing. Default: [].UrlLanguageManager
$keepUppercaseLanguageCodeboolWhether to keep uppercase letters of language codes in URLs. Default: false.UrlLanguageManager
$languageCookieDurationintLifetime of the language cookie in seconds; 0 disables the cookie. Default: 2592000.UrlLanguageManager
$languageCookieNamestringName of the language cookie. Default: '_language'.UrlLanguageManager
$languageCookieOptionsarrayAdditional Cookie properties for the language cookie. Default: [].UrlLanguageManager
$languageParamstringName of the createUrl() parameter that selects the language of the created URL. Default: 'language'.UrlLanguageManager
$languageRedirectCodeintHTTP status code of language redirects. Default: 302.UrlLanguageManager
$languagesarrayAvailable languages: codes (en-US), wildcards (es-*), or URL aliases mapped to codes ('english' => 'en'). Default: [].UrlLanguageManager
$languageSessionKeystring|boolSession key that stores the language; false disables session persistence. Default: '_language'.UrlLanguageManager
$normalizeryii\web\UrlNormalizer|array|string|falseThe configuration for UrlNormalizer used by this UrlManager. Default: false. Available since 2.0.10.yii\web\UrlManager
$routeParamstringThe GET parameter name for route. Default: 'r'.yii\web\UrlManager
$ruleConfigarrayThe default configuration of URL rules. Default: ['class' => 'yii\web\UrlRule'].yii\web\UrlManager
$rulesarrayThe rules for creating and parsing URLs when $enablePrettyUrl is true. Default: [].yii\web\UrlManager
$scriptUrlstringThe entry script URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
$showScriptNameboolWhether to show entry script name in the constructed URL. Default: true.yii\web\UrlManager
$suffixstringThe URL suffix used when $enablePrettyUrl is true. Default: null.yii\web\UrlManager
$_defaultLanguage protectedstringDefault language resolved by init() from $defaultLanguage or the application language. Default: ''.UrlLanguageManager
$cacheKey protectedstringThe cache key for cached rules Default: __CLASS__. Available since 2.0.8.yii\web\UrlManager
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addRules()Adds additional URL rules.yii\web\UrlManager
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
createAbsoluteUrl()Creates an absolute URL using the given route and query parameters.yii\web\UrlManager
createUrl()Creates a URL and inserts the language code after the base URL or the script name.UrlLanguageManager
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBaseUrl()Returns the base URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getDefaultLanguage()Returns the default language: $defaultLanguage, or the application language captured when the manager was initialized.UrlLanguageManager
getHostInfo()Returns the host info that is used by createAbsoluteUrl() to prepend to created URLs.yii\web\UrlManager
getScriptUrl()Returns the entry script URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Captures the default language and validates the configuration.UrlLanguageManager
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
parseRequest()Resolves the request language, removes its code from the path info, and parses the request.UrlLanguageManager
setBaseUrl()Sets the base URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
setHostInfo()Sets the host info that is used by createAbsoluteUrl() to prepend to created URLs.yii\web\UrlManager
setScriptUrl()Sets the entry script URL that is used by createUrl() to prepend to created URLs.yii\web\UrlManager
trigger()Triggers an event.yii\base\Component
buildRules() protectedBuilds URL rule objects from the given rule declarations.yii\web\UrlManager
canBeCached() protectedReturns the value indicating whether result of createUrl() of rule should be cached in internal cache.yii\web\UrlManager
detectLanguage() protectedDetects the language from the Accept-Language header, then from the GeoIP country.UrlLanguageManager
getBuiltRulesFromCache() protectedProvides the built URL rules that are associated with the $ruleDeclarations from cache.yii\web\UrlManager
getUrlFromCache() protectedGet URL from internal cache if exists.yii\web\UrlManager
loadPersistedLanguage() protectedReturns the language persisted in the session or, failing that, in the language cookie.UrlLanguageManager
matchCode() protectedMatches a language code against $languages, case-insensitively and including wildcards.UrlLanguageManager
persistLanguage() protectedStores the language in the session and the language cookie.UrlLanguageManager
processLocaleUrl() protectedResolves the language of the request and returns the language redirect it requires.UrlLanguageManager
setBuiltRulesCache() protectedStores $builtRules to cache, using $rulesDeclaration as a part of cache key.yii\web\UrlManager
setRuleToCache() protectedStore rule (e.g. UrlRule) to internal cache.yii\web\UrlManager
EventTypeDescriptionDefined by
EVENT_LANGUAGE_CHANGEDLanguageChangedEventRaised before a language from the URL that differs from the persisted one is persisted. Event name: 'languageChanged'.UrlLanguageManager
public string|null $defaultLanguage = null

Default language: the language of URLs without a code when $enableDefaultLanguageUrlCode is false.

null captures Yii::$app->language in init(). Set it explicitly in long-running workers, where the application object and its language persist between requests; it is also applied to Yii::$app->language at the start of each request.

public bool $enableDefaultLanguageUrlCode = false

Whether the default language uses a URL code like any other language.

When false, a URL without a code uses the default language, and a URL with the default code redirects to the URL without it (default fr: /fr/some/page -> /some/page), which also resets the persisted language. When true, a URL without a code redirects to the default code (/some/page -> /fr/some/page).

public bool $enableLanguageDetection = true

Whether to detect the language from the Accept-Language header when the URL has no code and no language is persisted.

GeoIP detection through $geoIpLanguageCountries applies regardless of this setting.

public bool $enableLanguagePersistence = true

Whether to persist the language from the URL in the session and the language cookie.

When true, a URL without a code redirects to the persisted language (/some/page -> /fr/some/page).

public $enablePrettyUrl = true

Whether to enable pretty URLs; must be true while locale URLs are enabled.

Declared without a native type to match UrlManager::$enablePrettyUrl.

public array $geoIpLanguageCountries = []

GeoIP country codes indexed by the language they select.

[
'de' => ['DEU', 'AUT'],
'ru' => ['RUS', 'BLR', 'KAZ'],
]
public string $geoIpServerVar = 'HTTP_X_GEO_COUNTRY'

Name of the server variable that carries the GeoIP country code.

Names starting with HTTP_ are read as the request header they represent (HTTP_X_GEO_COUNTRY -> X-Geo-Country); other names are read from getServerParams() when the request provides it, otherwise from $_SERVER.

public array $ignoreLanguageUrlPatterns = []

Regular expressions that exclude routes and URLs from language processing.

Keys match routes in createUrl(), which then adds no language code; values match the path info in parseRequest(), which then resolves no language.

The first pair assumes URL rules that map login and register to site/login and site/register.

[
'#^site/(login|register)#' => '#^(login|register)#',
'#^api/#' => '#^api/#',
]
public bool $keepUppercaseLanguageCode = false

Whether to keep uppercase letters of language codes in URLs.

When false, created URLs use lowercase codes, and a URL with an uppercase country (/de-AT/page) or with an alias spelled differently from its configuration (/AT/page) redirects to the lowercase URL.

public int $languageCookieDuration = 2592000

Lifetime of the language cookie in seconds; 0 disables the cookie.

Applies only when $enableLanguagePersistence is true.

public array $languageCookieOptions = []

Additional Cookie properties for the language cookie.

httpOnly defaults to true; name, value, and expire always come from $languageCookieName, the language, and $languageCookieDuration.

public string $languageParam = 'language'

Name of the createUrl() parameter that selects the language of the created URL.

URLs created with this parameter switch to that language; without it, the current application language is used.

public int $languageRedirectCode = 302

HTTP status code of language redirects.

Redirects caused only by the URL normalizer keep the normalizer status code.

public function createUrl(array|string $params): string

Creates a URL and inserts the language code after the base URL or the script name.

Parameters

ParameterTypeDescription
$paramsarray|stringRoute and parameters; $languageParam selects the language of the URL.

Returns

string: Created URL.

Throws

public function getDefaultLanguage(): string

Returns the default language: $defaultLanguage, or the application language captured when the manager was initialized.

Returns

string: Default language code, for example en.

public function init(): void

Captures the default language and validates the configuration.

Throws

public function parseRequest(yii\web\Request $request): array|bool

Resolves the request language, removes its code from the path info, and parses the request.

Each request object is processed once; later calls only parse it. A request not processed yet first resets Yii::$app->language to $defaultLanguage when it is set. When the request must move to its canonical language URL, UrlNormalizerRedirectException carries the target URL and $languageRedirectCode, or the normalizer status code when only the URL normalizer requires the redirect. A redirect raised by a URL rule with a string URL is rethrown unchanged.

Parameters

ParameterTypeDescription
$requestyii\web\RequestRequest to parse.

Returns

array|bool: Route and parameters, or false if no rule matches the request.

Throws

protected function detectLanguage(yii\web\Request $request): string|null

Detects the language from the Accept-Language header, then from the GeoIP country.

Parameters

ParameterTypeDescription
$requestyii\web\RequestRequest that provides the header and the GeoIP country.

Returns

string|null: Detected language code, or null if no configured language matches.

protected function loadPersistedLanguage(yii\web\Request $request): string|null

Returns the language persisted in the session or, failing that, in the language cookie.

Parameters

ParameterTypeDescription
$requestyii\web\RequestRequest that provides the language cookie.

Returns

string|null: Persisted language code, or null if none is stored.

protected function matchCode(string $code): array

Matches a language code against $languages, case-insensitively and including wildcards.

Exact matches skip wildcards and return the configured spelling. A wildcard match (es-*) returns the configured spelling of the language and the first subtag when it is a 2-3 letter region, in uppercase: ES-mx-variant -> ['es', 'MX']; any other subtag is dropped: es-Latn -> ['es', null]. A code whose region is not configured falls back to its language when that language is configured: de-CH -> ['de', null].

Parameters

ParameterTypeDescription
$codestringLanguage code to match, for example en, en-US, or es-MX.

Returns

array: Matched language and country, or [null, null] if no configured language matches.

protected function persistLanguage(yii\web\Request $request, string $language): void

Stores the language in the session and the language cookie.

Triggers EVENT_LANGUAGE_CHANGED first when handlers are attached and the language differs from the persisted one.

Parameters

ParameterTypeDescription
$requestyii\web\RequestRequest that provides the previously persisted language.
$languagestringLanguage code to persist, for example en or de-AT.
protected function processLocaleUrl(yii\web\Request $request): string|null

Resolves the language of the request and returns the language redirect it requires.

A language code at the start of the path info is removed from it, applied to Yii::$app->language, and persisted. Without a code, the persisted language, then the detected language, then (with $enableDefaultLanguageUrlCode) the default language selects the redirect target.

Parameters

ParameterTypeDescription
$requestyii\web\RequestRequest whose path info is processed.

Returns

string|null: Language code or alias to redirect to, '' to redirect to the URL without a language code, or null if no language redirect is required.

Throws