如何修复 Symfony v2.8 "Creating/Configuring Services in the Container" 'autoloader expected class ...'



很长一段时间以来,我一直在试图了解如何添加我自己的函数库,我想在我的Web应用程序的不同控制器/捆绑包中使用,但我只是发现我需要"容纳"这些功能一个Symfony服务容器。

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

为了更好地处理这个问题,我尝试了Symfony v2.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 AppBundleService;
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];
}
}

然后,我将以下内容添加到服务配置文件中:

# app/config/services.yml
services:
app.message_generator:
class:     AppBundleServiceMessageGenerator
arguments: []

然后我将以下行放在以前工作的控制器/捆绑包中:

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

当我上传这些文件并运行相关的网页时,我得到了:

The autoloader expected class "AppBundleServiceMessageGenerator" 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 未在 MessageGenerator.php 文件中定义,因为该文件由于缺少

MessageGenerator.php 文件丢失

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

行已执行,并且$generatedMessage包含数组元素消息之一,正如预期的那样。

最新更新