Не могу заставить мою почтовую службу работать в Symfony 4 - PullRequest
0 голосов
/ 20 октября 2018

Я не могу заставить мой почтовик работать при создании службы.

Я следовал нескольким учебникам.Я пытался внедрить свои зависимости, но у меня не получается заставить $this->container->render() работать

. Я получаю следующее сообщение об ошибке

ServiceNotFoundException: Сервисное приложение\ Services \ Mailer "зависит от несуществующего сервиса" templating ".

Что было бы хорошим способом внедрить службу шаблонов в мой сервис Mailer?Я знаю, что это называется внедрением зависимостей, но я не могу заставить его работать должным образом.

Я пытался следовать этому, но безуспешно: RenderView в Моем сервисе

Мой контроллер:

use App\Services\Mailer;

class ScriptController extends AbstractController
{
    private function getThatNotifSent($timeframe, Mailer $mailer)
    {
        // Some code

        foreach ( $users as $user ) {
            $mailer->sendNotification($user, $cryptos, $news, $timeframe);
            $count++;
        }

        $response = new JsonResponse(array('Mails Sent' => $count));
        return $response;
    }
}

Мой сервис:

<?php
// src/Service/Mailer.php

namespace App\Services;

use Symfony\Component\DependencyInjection\ContainerInterface;


class Mailer
{
    private $mailer;
    private $templating;

    public function __construct(\Swift_Mailer $mailer ,ContainerInterface $templating)
    {
        $this->mailer = $mailer;
        $this->templating = $templating;
    }
    public function sendNotification($user, $cryptos, $news, $timeframe)
    {
        $message = (new \Swift_Message('Your Daily Digest Is Here!'))
            ->setFrom('no-reply@gmail.com')
            ->setTo($user->getEmail())
            ->setBody(
                $this->templating->render(
                    'emails/notification.html.twig',
                    array(
                        'timeframe' => $timeframe,
                        'cryptos' => $cryptos,
                        'user' => $user,
                        'news' => $news,
                    )
                ),
                'text/html'
            )
            ->setCharset('utf-8');

        $this->mailer->send($message);
        return true;
    }
}

Мой сервис.yaml

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'en'
    images_directory: '%kernel.project_dir%/public/images/blog'

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.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

    # 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/{Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    App\EventListener\LoginListener:
        tags:
            - { name: 'kernel.event_listener', event: 'security.interactive_login' }

    App\Services\Mailer:
          arguments: ["@mailer", "@templating”]

ОБНОВЛЕНИЕ:

Я обновил свой код, чтобы следоватьТайлан ответ.Мой почтовый сервис теперь выглядит следующим образом (без изменений в sendNotification Made)

<?php
// src/Service/Mailer.php

namespace App\Services;

use Symfony\Bundle\TwigBundle\TwigEngine;


class Mailer
{
    private $mailer;
    private $templating;

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

У меня все еще было то же сообщение об ошибке.Но после проведения онлайн-исследований я обновил свой framework.yaml после прочтения этой полезной ссылки: https://github.com/whiteoctober/BreadcrumbsBundle/issues/85

framework:
    templating: { engines: [twig] }

Это сработало

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 21 октября 2018

Типовое указание ContainerInterface дает вам контейнер, но вы назвали его $templating.Вы должны получать шаблоны из контейнера, как этот $this->templating = $container->get('templating').

Но вам действительно нужен контейнер?Вы должны иметь возможность внедрять шаблоны непосредственно, печатая так: Symfony\Bundle\TwigBundle\TwigEngine $templating вместо Symfony\Component\DependencyInjection\ContainerInterface $container.

PS: Вы можете искать службы с помощью команды php bin/console debug:container.

...