我们基本上具有与this example相同的配置和模式:
[
'translator' => [
'locale' => 'en_US',
'translation_file_patterns' => [
[
'base_dir' => __DIR__ . '/../languages/phpArray',
'type' => 'phpArray',
'pattern' => '%s.php',
],
[
'base_dir' => __DIR__ . '/../languages/gettext',
'type' => 'gettext',
'pattern' => '%s.mo',
],
],
],
]
我需要从翻译器中获取所有已加载语言环境的列表,以便构建语言选择器。稍后我们将添加更多的语言环境,我希望根据可用的翻译保持动态。
这有可能吗?
答案 0 :(得分:0)
好吧,我发现这是一个有趣的挑战,所以我做到了:)
请注意,在配置中和问题中一样,将语言环境设置为en_US
。如果您允许用户选择区域设置,则必须动态更新此设置(这不是我为您创建的;-))
我创建的内容使用FilesystemCache。如果愿意,您可以使用其他东西。
为了测试,我在随机模块的language/
文件夹中创建了一些文件:
(请注意,上面使用了不同的分隔符)
必需的配置
'caches' => [
'FilesystemCache' => [
'adapter' => [
'name' => Filesystem::class,
'options' => [
// Store cached data in this directory.
'cache_dir' => './data/cache',
// Store cached data for 1 hour.
'ttl' => 60*60*1
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [
],
],
],
],
],
'service_manager' => [
'factories' => [
LocaleOptionsManager::class => LocaleOptionsManagerFactory::class,
],
],
因此,这里有些事情应该变得清楚了。使用data/cache/
作为缓存目录。我还创建了一个LocaleOptionsManager
和一个工厂。
LocaleOptionsManager
<?php
namespace User\Service;
use Zend\Cache\Storage\StorageInterface;
class LocaleOptionsManager
{
/**
* @var StorageInterface
*/
protected $cache;
/**
* @var array
*/
protected $config;
public function __construct(StorageInterface $cache, array $config)
{
$this->setCache($cache);
$this->setConfig($config);
}
/**
* @param bool $forceCreate
*
* @return array
*/
public function __invoke(bool $forceCreate = false) : array
{
if ($forceCreate) {
// Must recreate cache - remove current locale options
$this->getCache()->removeItem('locale_options');
}
// Loads locale options from cache into $cache. Result (bool) of whether action succeeded loaded into $result
$cache = $this->getCache()->getItem('locale_options', $result);
if ($result) {
// Loading cache (above) succeeded, return cache contents
return $cache;
}
// Above loading of cache didn't succeed or didn't exist, create new cache
$options = [];
foreach ($this->getConfig() as $config) {
if (
array_key_exists('base_dir', $config)
&& isset($config['base_dir'])
&& array_key_exists('pattern', $config)
&& isset($config['pattern'])
) {
// str_replace used to replace "%s" with "*" to make it a regex pattern accepted by glob()
foreach (glob(str_replace('%s', '*', $config['base_dir'] . DIRECTORY_SEPARATOR . $config['pattern'])) as $fileName) {
// Specifically returns filename without extension - see: http://php.net/manual/en/function.pathinfo.php
$options[] = pathinfo($fileName, PATHINFO_FILENAME);
}
}
}
// Save supported locales to cache
if ($this->getCache()->setItem('locale_options', $options)) {
return $options;
}
return [];
}
/**
* @return StorageInterface
*/
public function getCache() : StorageInterface
{
return $this->cache;
}
/**
* @param StorageInterface $cache
*
* @return LocaleOptionsManager
*/
public function setCache(StorageInterface $cache) : LocaleOptionsManager
{
$this->cache = $cache;
return $this;
}
/**
* @return array
*/
public function getConfig() : array
{
return $this->config;
}
/**
* @param array $config
*/
public function setConfig(array $config) : void
{
$this->config = $config;
}
}
如您所见,真正的作用在于该__invoke
函数。内联评论应解释发生了什么,如果您有任何疑问,请提出疑问!
LocaleOptionsManagerFactory
<?php
namespace User\Factory\Service;
use Interop\Container\ContainerInterface;
use User\Service\LocaleOptionsManager;
use Zend\Cache\Storage\StorageInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class LocaleOptionsManagerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$config = $container->get('Config');
/** @var StorageInterface $cache */
$cache = $container->get('FilesystemCache');
if (
array_key_exists('translator', $config)
&& array_key_exists('translation_file_patterns', $config['translator'])
&& count($config['translator']['translation_file_patterns']) > 0
) {
return new LocaleOptionsManager($cache, $config['translator']['translation_file_patterns']);
}
return new LocaleOptionsManager($cache, []);
}
}
为确保配置了任何翻译器的 not 不会使应用程序崩溃,我们为它提供了一个空数组作为第二个参数。如果您查看实际的类,那么只要存在,它就会将一个空数组设置为缓存(并返回该数组)。
好吧,很容易,就像您选择其他Select一样,只需要提供值即可。
表单构造函数&& init()
public function __construct($name = null, array $options = [])
{
if ( ! array_key_exists('locale_options', $options)) {
throw new Exception('Locale options not received. Are you a teapot?', 418);
}
parent::__construct($name, $options);
}
public function init()
{
$this->add(
[
'name' => 'language',
'required' => true,
'type' => Select::class,
'options' => [
'label' => _('Select language'),
'value_options' => $this->options['locale_options'],
],
]
);
// other fields
}
我使用通用的Factory来生成我的表单和字段集(如果需要,请参见我的github),但是要添加这些选项,我做到了:
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) : AbstractForm
{
$localeOptions = $container->get(LocaleOptionsManager::class);
$options = [];
// set key/value to same string (a Select has the "key" as the 'value' in the HTML)
foreach ($localeOptions() as $option) {
$options['locale_options'][$option] = $option;
}
$this->options = $options;
// THIS IS MY GENERIC INVOKE - CREATE YOUR OWN FORM HERE
return parent::__invoke($container, $requestedName, $options);
}
所有这些使我在下图中得到了结果: