Symfony的现有公共服务引发的错误消息“您请求一个不存在的服务”
我开始与Symfony的服务工作,并因此创造了从symfony的文档,示例服务:Symfony的现有公共服务引发的错误消息“您请求一个不存在的服务”
namespace AppBundle\Service;
use Psr\Log\LoggerInterface;
class MessageGenerator
{
private $logger;
public function __construct(LoggerInterface $logger){
}
public function getMessage()
{
$this->logger->info('Success!');
}
}
我称之为在我的控制器服务(我也有使用说明: :use AppBundle\Service\MessageGenerator;
$messageGenerator = $this->get(MessageGenerator::class);
$message = $messageGenerator->getMessage();
$this->addFlash('success', $message);
我的服务就是在services.yml文件中定义:
app.message_generator:
class: AppBundle\Service\MessageGenerator
public: true
所以在我的眼里,我做了完全一样的文档中描述的一切,打电话时:
php app/console debug:container app.message_generator
在我的命令行
我让我的服务:
Option Value
------------------ ------------------------------------
Service ID app.message_generator
Class AppBundle\Service\MessageGenerator
Tags -
Scope container
Public yes
Synthetic no
Lazy no
Synchronized no
Abstract no
Autowired no
Autowiring Types -
现在,当我执行控制器功能,我打电话给我的服务我仍然得到错误:
You have requested a non-existent service "appbundle\service\messagegenerator".
任何ide如?
Symfony在命名时有点混乱:您通过请求它的定义名称来获取服务:app.message_generator
。
$messageGenerator = $this->get('app.message_generator');
Symfony的最近建议从正在定义的服务为,类名(AppBundle\Service\MessageGenerator
)一个给名(app.message_generator
)开关。他们都只是一个叫'服务'的名字。
当您仅定义给定名称时,您正在尝试使用这两种方法。
从长远来看,建议使用基于::class
的名称,并且很可能允许框架自己查找类,并自行配置它们。这意味着,默认情况下,所有服务都是私有的,并且由服务容器框架&处理。
在此期间,在你学习,你可以:
$messageGenerator = $this->get('app.message_generator');
或定义明确定义的服务,并予以公布,以便它能与->get(...)
从容器中取出。
# services.yml
AppBundle\Service\MessageGenerator:
class: AppBundle\Service\MessageGenerator
public: true
# php controller
$messageGenerator = $this->get(MessageGenerator::class);
或只是自动注入到控制器,即要求
public function __construct(LoggerInterface $logger, MessageGenerator $msgGen)
{
$this->messageGenerator = $msgGen;
}
public function getMessage()
{
$result = $this->messageGenerator->do_things(....);
$this->logger->info('Success!');
}
谢谢你的回答,它也能解决我的问题,但是Sics更快,所以我接受了他的回答。 :) – sonja
时,或作为替代方案,在服务定义文件中的类名称替换app.message_generator。这反过来可以让你消除类:线,也更符合最新的集装箱推荐做法。 – Cerad
谢谢@sics,解决了我的问题! – sonja