Я пытаюсь перейти с Symfony 3.4 на Symfony 4.1, но у меня проблема с autowire. У меня установлен пакет symfony / swiftmailer, а в подписчике событий у меня есть:
public function __construct(\Swift_Mailer $mailer, EngineInterface $templating, EntityManagerInterface $em, $senderMail, $senderName)
{
$this->mailer = $mailer;
$this->templating = $templating;
$this->em = $em;
$this->senderMail = $senderMail;
$this->senderName = $senderName;
}
В service.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'
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
# Twig
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
# Listeners
App\EventListener\ContactNotificationSubscriber:
$senderMail: '%env(MAILER_SENDER_ADDRESS)%'
$senderName: '%env(MAILER_SENDER_NAME)%'
Но у меня ошибка:
Cannot autowire service "App\EventListener\ContactNotificationSubscriber": argument "$mailer" of method "__construct()" references class "Swift_Mailer" but no such service exists.
Я не понимаю, почему ... Компонент существует, с PhpStorm я могу щелкнуть \ Swift_Mailer и увидеть класс, но Symfony всегда возвращает мне ошибку ...
Если кто знает почему :-) Большое спасибо
Если бы мне пришлось угадывать, я бы сказал, что вы не обновляли пакет быстрой рассылки. Следовательно, услуги не существует. У вас должна быть v3.2.2
Я нашел, но, возможно, есть способ сделать это автоматически, я использую команду symfony: composer create-project symfony/website-skeleton my_project для установки нового проекта, затем я копирую / вставляю весь файл composer.json в свой старый проект и тогда используйте composer update, composer require для пакетов, которые я использую в своем проекте. Фактически, он устанавливает пакет symfony / swiftmailer, но не его зависимости .... Есть ли способ сделать это? Я сделал composer remove symfony/swiftmailer_bundle, затем composer require symfony/swiftmailer_bundle. Но я сомневаюсь во всех остальных зависимостях ...
Это может быть сложно. Мне больше всего удалось создать новый проект, установить все дополнительные зависимости, а затем скопировать composer.json обратно в существующий проект. А потом все исправить.
Проверьте symfony.com/doc/current/service_container/… Псевдоним может решить эту проблему.
Наконец, я воссоздаю новый проект с помощью symfony 4.1 и делаю выборку, чтобы вставить свой собственный код, после чего исправляю некоторые ошибки. Оно работает.




У меня была такая же проблема. В моем случае этот комплект не был включен в bundles.php. Добавление следующего в bundles.php решило эту проблему для меня:
Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true],
Запустите «bin / console debug: container Swift_Mailer» и убедитесь, что у вас есть служба под названием Swift_Mailer. И убедитесь, что ваши свойства senderMail / Name имеют правильный отступ.