menencia/locale-detector

此包的最新版本(0.1.2)没有可用的许可信息。

区域检测器

此包的官方仓库似乎已消失,因此该包已被冻结。

0.1.2 2017-12-06 16:15 UTC

This package is not auto-updated.

Last update: 2021-08-01 23:56:49 UTC


README

使用此模块,您可以首先获取用户检测到的区域,具体取决于您想要什么。

调用此模块

$localeDetector = new Menencia\LocaleDetector\LocaleDetector();

这是实际的策略顺序,但您可以重新排序此数组或删除某些项目

$localeDetector->setOrder(['TLD', 'Cookie', 'Header', 'NSession']); // optional
  • 顶级域名(TLD):从 $_SERVER['SERVER_NAME'] 确定区域
  • Cookie:从 $_COOKIE[$field] 确定区域
  • Header:从 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 确定区域
  • NSession(会话):从 $_SESSION[$field] 确定区域
  • IP(IP地址):从 $_SERVER['REMOTE_ADDR'] 确定区域
  • 默认情况下,从 Locale::getDefault() 确定区域

默认情况下,$field = 'lang';。这是您更改它的方法

Cookie::$fieldName = 'newFieldName';
NSession::$fieldName = 'newFieldName';

然后,您只需调用检测方法并检索区域

$locale = $localeDetector->detect();

高级策略

您可以根据需要自定义策略,如下所示

$localeDetector->addCallback('MyCallback', function($a){
    return collator_create($a);
}, ['fr-FR']);

$localeDetector->setOrder(['MyCallback']);

也许您想要扩展策略接口

<?php

class MyStrategy implements IStrategy
{

    public function getName() {
        return 'MyStrategy';
    }

    public function detect() {
        return collator_create('fr-FR');
    }

}

然后,您将其添加到注册中

$localeDetector->registerStrategy(new MyStrategy);

$localeDetector->setOrder(['MyStrategy']);