Symfony 5.4 - 公共服务似乎不起作用

Symfony 5.4 - Public services do not seem to work

提问人:Nicholas Robertson 提问时间:9/20/2023 更新时间:9/20/2023 访问量:53

问:

公共服务似乎被打破了

错误:

未找到服务“BaseService”:即使它存在于应用程序的容器中,“classes\classBundle\Controller\DefaultController”中的容器也是一个较小的服务定位器,它只知道“doctrine”、“form.factory”、“http_kernel”、“message_bus”、“messenger.default_bus”、“parameter_bag”、“request_stack”、“router”、“security.authorization_checker”、“security.csrf.token_manager”、“security.token_storage”、“serializer”、“session”和“twig”服务。请尝试改用依赖项注入。

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Services/'
    classes\:
        resource: '../bundles/classes'
    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    BaseService:
        class: App\Services\BaseService
        public: true

以下是服务。最简单的例子。我必须将一堆旧的 Symfony 代码移动到 5.4,在最初的项目中,它们都是公开的(最初是 Symfony 3)。

<?php
namespace App\Services;

class BaseService
{

}

控制器:

<?php

namespace classes\classBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as Controller;
use App\Service\BaseService;
class DefaultController extends Controller
{
    public function index()
    {
        $this->get("BaseService");
        return new Response("test");
    }
}
Symfony 服务 公共

评论

1赞 Skuti 9/20/2023
我认为你应该忘记使用 $this->get('something')。将默认值设置为 autowire 和 autoconfigure,然后只需通过控制器的方法签名或服务的构造函数注入服务

答:

0赞 amama wissem 9/20/2023 #1

当你启动一个Symfony应用程序的那一刻,你的容器已经包含了许多服务。因此,如果您需要在控制器中使用服务,只需键入一个带有其类(或接口)名称的参数提示即可。Symfony会自动为您提供所需的服务。

您可以阅读有关此内容的更多信息: