【发布时间】:2019-09-13 06:53:38
【问题描述】:
很长一段时间以来,我一直在尝试了解如何添加我自己的函数库,这些函数库要在我的 Web 应用程序的不同控制器/包中使用,但我只是发现我需要“容纳”这些函数Symfony 服务容器。
与其他计算机语言不同,服务不是后台进程!
为了更好地处理这个问题,我尝试了Creating/Configuring Services in the Container 上的 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 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];
}
}
然后我将以下内容添加到服务配置文件中:
# app/config/services.yml
services:
app.message_generator:
class: AppBundle\Service\MessageGenerator
arguments: []
然后我将以下几行放在以前可以正常工作的控制器/捆绑包中:
$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.
此消息似乎表明在 src/AppBundle/Service 目录中找到了 MessageGenerator.php 文件。但是 MessageGenerator 类未在 MessageGenerator.php 文件中定义,因为该文件由于缺少而未被识别为 php 文件
【问题讨论】:
标签: php service symfony-2.8