Symfony 4.0 Translator类未注入控制器

时间:2017-12-08 09:40:01

标签: dependency-injection symfony4

我在新的symfony 4中遇到了问题。

<?php

namespace App\Controller;

use App\Entity\Flight;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Form\FlightType;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultController
 * @package App\Controller
 */
class DefaultController extends Controller
{
    /**
     * 
     * @Route("/")
     * @Route("/{_locale}/", name="homepage", requirements={"_locale" = "%app.locales%"})
     * 
     * @param Translator $translator
     * @param Request $request
     * 
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function index(Translator $translator, Request $request)
    {
        $translated = $translator->trans('Symfony is great');

错误: 控制器“App \ Controller \ DefaultController :: index()”要求您为“$ translator”参数提供值。参数可以为空,并且没有提供空值,没有提供默认值,或者因为在此之后存在非可选参数。

CONFIGS: service.yaml

services:    
    _defaults:
        autowire: true    
        autoconfigure: true 
        public: false

...
App\Controller\:
    autowire: true       
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

translation.yaml

framework:
    default_locale: '%locale%'
    translator:
        paths:
            - '%kernel.project_dir%/translations'
        fallbacks: ['en']    

什么错了?手册在这里: http://symfony.com/doc/current/translation.html

1 个答案:

答案 0 :(得分:2)

找到答案。

  1. bin / console cache:clear没有清除消息缓存。帮助刚刚删除var / cache文件夹。
  2. 我使用Action(TranslatorInterface $ translator)注入控制器操作(可能是文档中的错误)
  3. $ translator-&gt; trans(&#39; id&#39;)不能使用ID。它在使用跨单位标签时起作用。