Zend\Mvc\Controller\PluginManager::get 无法获取或创建翻译实例

Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for translate

我已经编写了一个控制器插件来使用 ZF 2.5 获取 MVC 转换器。

这是我的翻译控制器插件

namespace Freedom\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\I18n\Translator\Translator;

/**
 * Translate
 *
 */
class Translate extends AbstractPlugin
{

    /**
     *
     * @var Translator
     */
    private $translator;

    public function __construct(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Translate message
     * @param string $message
     * @param string $textDomain
     * @param string $locale
     * @return string
     */
    public function __invoke($message, $textDomain = 'default', $locale = null)
    {
        return $this->translator->translate($message, $textDomain, $locale);
    }

    /**
     *
     * @return Translator
     */
    function getTranslator()
    {
        return $this->translator;
    }

}

并且是工厂

namespace Freedom\Controller\Plugin\Service;

use Zend\ServiceManager\FactoryInterface;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Freedom\Controller\Plugin\Translate;

/**
 * TranslateFactory
 *
 */
class TranslateFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new Translate($container->get('translator'));
    }

    public function createService(ServiceLocatorInterface $container)
    {
        return $this($container->getServiceLocator(), Translate::class);
    }
}

最后在我的 module.config

'controller_plugins' => [
    'factories' => [
        'checkRedirect' => 'Freedom\Controller\Plugin\Service\CheckRedirectFactory',
        'translate' => 'Freedom\Controller\Plugin\Service\TranslateFactory',
    ],
],

我遇到的问题是出现此错误,我不明白为什么。

Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for translate

如您所见,我已经在 module.config 中注册了该插件,但插件管理器找不到它。我已经检查过 controller_plugins 密钥存在于配置中并且我的命名空间是正确的。我还有另一个名为 checkRedirect 的插件会产生相同的错误。

我完全搞不懂这是怎么回事,请有人告诉我我错过了什么,非常感谢。

请试试这个,也许对你有帮助。

我觉得一切正常,但你需要更新这个,

'controller_plugins' => [
    'factories' => [
        'checkRedirectPlugin' => 'Freedom\Controller\Plugin\Service\CheckRedirectFactory',
        'translatePlugin' => 'Freedom\Controller\Plugin\Service\TranslateFactory',
    ],
   'aliases' =>[
       'checkRedirect' => 'checkRedirectPlugin',
        'translate' => 'translatePlugin'
    ]

],

现在使用别名,您现在可以从您的控制器访问,

$this->translate()

我终于找到了问题所在,我是从 controllers constructor 调用插件,但它不起作用。从一个动作中调用,一切正常。