首页 > 解决方案 > 无法自动装配服务“App\Service\MatchCarAdService”:方法的参数“$template”

问题描述

嗨,我正在创建一项服务。这是代码,

namespace App\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\CarAd;

class MatchCarAdService {

    protected $mailer;
    protected $templating;


    public function __construct(ContainerInterface $container, \Swift_Mailer $mailer, $templating) {
        $this->container = $container;
        $this->mailer = $mailer;
        $this->templating = $templating;
    }

    public function sendMail() {
        $message = (new \Swift_Message('Hello Email'))
                ->setFrom('vimuths@yahoo.com')
                ->setTo('vimuths@yahoo.com')
                ->setBody(
                $this->templating->render(
                        // templates/emails/matching-cars.html.html.twig
                        'emails/matching-cars.html.html.twig', []
                ), 'text/html'
        );

    $this->mailer->send($message);

这是 services.yml

MatchCarAdService:
            class: App\Service\MatchCarAdService
            arguments: ['@mailer','@templating']

但是我收到了这个错误,

无法解析“App\Controller\Api\SearchController()”的参数 $matchService:无法自动连接服务“App\Service\MatchCarAdService”:方法“__construct()”的参数“$templating”没有类型提示,您应该配置它的价值明确。

标签: phpsymfony

解决方案


Symfony 3.3+ 答案

由@M 回答。Kebza 解决了您的问题。但是您可以使这更加简单和防错误。只需使用 Symfony 3.3+ 的功能。

A. 使用自动装配

services:
    _defaults:
        autowire: true

    App\Service\MatchCarAdService: ~
    App\Service\CleaningService: ~
    App\Service\RentingService: ~

B. 使用自动装配 + 自动发现 - 更好!

services:
    _defaults:
        autowire: true

    App\:
        resource: ../src

这会按照PSR-4 约定App\从目录加载命名空间中的所有服务。../src

您可以在 Symfony 3.3 中的 How to refactor to new Dependency Injection features 中看到更多示例。


推荐阅读