easyswoole-tool/hyperf-translation

dev-master 2021-09-12 14:14 UTC

This package is auto-updated.

Last update: 2024-11-12 20:52:53 UTC


README

EasySwoole Hyperf Translation


Install

The preferred way to install this extension is through composer.

Either run

composer require easyswoole-tool/hyperf-translation dev-master

or add

"easyswoole-tool/hyperf-translation": "dev-master"

to the require section of your composer.json file.

Config

// dev.php

    <?php
    
    return [
        'locale' => 'zh_CN',
        'fallback_locale' => 'en',
        'path' => EASYSWOOLE_ROOT . '/storage/languages',
    ];

DI

// Container.php

<?php
declare(strict_types=1);

use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use Psr\Container\ContainerInterface;
use Throwable;

class Container implements ContainerInterface
{
    use Singleton;

    /**
     * @param string $id
     * @return callable|mixed|string|null
     * @throws Throwable
     */
    public function get($id)
    {
        return Di::getInstance()->get($id);
    }

    /**
     * @param string $id
     * @return callable|mixed|string|null
     * @throws Throwable
     */
    public function has($id)
    {
        return Di::getInstance()->get($id) != null;
    }

    /**
     * @param string $name
     * @param array  $parameters
     *
     * @return null
     * @throws Throwable
     */
    public function make(string $name, array $parameters = [])
    {
        $data = Di::getInstance($parameters)->get($name);
        if (is_null($data)) {
            $parameters = array_values($parameters);
            $data = new $name(...$parameters);
        }
        return $data;
    }
}

// EasySwooleEvent.php

    use Hyperf\Contract\TranslatorInterface;
    use EasySwoole\Hyperf\Translation\Translator;
    use EasySwoole\Component\Di;
    use Hyperf\Utils\ApplicationContext;
    use Psr\Container\ContainerInterface;
    
    Di::getInstance()->set(ContainerInterface::class, Container::class);
    ApplicationContext::setContainer(Di::getInstance()->get(ContainerInterface::class));
    Di::getInstance()->set(TranslatorInterface::class, Translator::class);

Use

    echo __('messages.welcome', [], 'zh_CN');

See Translation other document.