Php 如何修复Symfony v2.8“;“在容器中创建/配置服务”';自动加载器预期等级…';错误

Php 如何修复Symfony v2.8“;“在容器中创建/配置服务”';自动加载器预期等级…';错误,php,service,symfony-2.8,Php,Service,Symfony 2.8,很长一段时间以来,我一直在试图理解如何添加我自己的函数库,以便在我的Web应用程序的不同控制器/捆绑包中使用,但我只是发现我需要将这些函数“装入”一个Symfony服务容器 与其他计算机语言不同,服务不是后台进程 为了更好地处理这个问题,我在上的symfonyv2.8指南部分中尝试了这个示例。我在建议的目录中创建了以下文件: <?php // <=== This was missing from the MessageGenerator.php file! //

很长一段时间以来,我一直在试图理解如何添加我自己的函数库,以便在我的Web应用程序的不同控制器/捆绑包中使用,但我只是发现我需要将这些函数“装入”一个Symfony服务容器

与其他计算机语言不同,服务不是后台进程

为了更好地处理这个问题,我在上的symfonyv2.8指南部分中尝试了这个示例。我在建议的目录中创建了以下文件:

<?php  // <=== This was missing from the MessageGenerator.php file!
       //
       // Adding it to the file solved the autoloader error, and now the MessageGenerator
       // class loads properly!
       //

// src/AppBundle/Service/MessageGenerator.php

namespace AppBundle\Service;

class MessageGenerator {
    public function getHappyMessage() {
        $messages = [
            'You did it! You updated the system! Amazing!',
            'That was one of the coolest updates I\'ve seen all day!',
            'Great work! Keep going!'
        ];

        $index = array_rand($messages);

        return $messages[$index];
    }
}
然后,我将以下几行放在一个控制器/捆绑包中,否则以前是可以工作的:

$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
当我上传这些文件并运行相关网页时,我得到:

The autoloader expected class "AppBundle\Service\MessageGenerator" to be defined in
file "/var/www/vhosts/symfony2/vendor/composer/../../src/AppBundle/Service/
MessageGenerator.php". The file was found but the class was not in it, the class name
or namespace probably has a typo.

此消息似乎表示MessageGenerator.php文件位于src/AppBundle/Service目录中。但是,MessageGenerator.php文件中未定义MessageGenerator类,因为由于缺少MessageGenerator.php文件,该文件未被识别为php文件
$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();
行被执行,$generatedMessage包含一条数组元素消息,如预期的那样

$messageGenerator = $this->container->get( 'app.message_generator' );
$generatedMessage = $messageGenerator->getHappyMessage();