找不到服务:即使它存在于应用程序的容器中 [英] Service not found: even though it exists in the app's container

查看:22
本文介绍了找不到服务:即使它存在于应用程序的容器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么:

services.yaml:

app.foo.bar:
    class: App\Foo\Bar
    arguments: #[ ... ]

控制器:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function baz(Request $request)
    {
        $this->get('some_bundle.some_service');
    }
}

它有效.

但是由于 Symfony\Bundle\FrameworkBundle\Controller\Controller 已被弃用,我尝试扩展 Symfony\Bundle\FrameworkBundle\Controller\AbstractController 并且我得到了

But as Symfony\Bundle\FrameworkBundle\Controller\Controller is deprecated, I've tried to extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController and I got

未找到服务some_bundle.some_service":甚至虽然它存在于应用程序的容器中,但里面的容器App\Controller\MyController"是一个较小的服务定位器只知道 "doctrine", "http_kernel", "parameter_bag",request_stack"、router"、serializer"和session"服务.尝试改用依赖注入.

Service "some_bundle.some_service" not found: even though it exists in the app's container, the container inside "App\Controller\MyController" is a smaller service locator that only knows about the "doctrine", "http_kernel", "parameter_bag", "request_stack", "router", "serializer" and "session" services. Try using dependency injection instead.

我可以以某种方式将 get()AbstractController 一起使用吗?AbstractController 使用了 ControllerTrait,不知道为什么会出现这个错误.

Can I use get() somehow with AbstractController? AbstractController uses ControllerTrait, I wonder why the error takes place.

推荐答案

symfony4 与以前的版本相比有很多变化.您正在使用所有内容,就像在以前的版本中一样.快速解决方案不是首选"方式,但开始时可以将服务中的 public 键从默认的 false 更改为 true.yaml 文件.

A lot of things changed in symfony4 vs previous versions. You are using everything as if in a previous version. The quick solution is not the "preferred" way, but to start can change the public key from the default false to true in your services.yaml file.

更好的方法是将其保留为私有并使用依赖注入.服务的命名也发生了变化(现在只是服务的路径).请参阅此处的文档.对于您的代码,请尝试以下操作:

A better way is to leave it private and use dependency injection instead. The naming of the service has changed as well (now just the path of the service). See the docs here. For your code, try these:

// services.yaml

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

    App\Foo\Bar:
        tags: { ** }

以及具有依赖注入的控制器:

And the controller with dependence injection:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    public function baz(Request $request, Bar $bar)
    {
        $bar->doSomething();
    }
}

有一个关于这些东西(以及更多)的很好的教程这里.

There's a nice tutorial about these things (and more) here.

这篇关于找不到服务:即使它存在于应用程序的容器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆