Вызов экшена контроллера из консоли в Symfony

Реализовывается достаточно просто:

<?php
declare(strict_types=1);

namespace App\Command;

use App\Controller\BackOfficeController;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

// bin/console app:production-preparation

#[AsCommand(
    name: 'app:production-preparation',
    description: 'Подготавливает прод',
)]
class ProductionPreparationCommand extends Command
{
    public function __construct(
        private readonly BackOfficeController $backOfficeController,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        //------------------------ создаем шаблоны для 404 и любых других ошибок: ----------------------------
        $response = $this->backOfficeController->system_error('404')->getContent();
        file_put_contents('/app/backend/templates/bundles/TwigBundle/Exception/error404.html.twig', $response);

        $response = $this->backOfficeController->system_error('other')->getContent();
        file_put_contents('/app/backend/templates/bundles/TwigBundle/Exception/error.html.twig', $response);

        return Command::SUCCESS;
    }
}

Второй способ - который я не стал использовать (причину уже не помню):

#!/usr/bin/env php
<?php

use App\Kernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

//-------------- создаем шаблоны, которые не нужно более никак обрабатывать для 404 и любых других ошибок: -------------
require_once __DIR__.'/../config/autoload.php';

$kernel = new Kernel('prod', false);

$request = Request::create('/hidden/system/error/404');
$response = $kernel->handle($request, HttpKernelInterface::MAIN_REQUEST, false);
file_put_contents('/app/backend/templates/bundles/TwigBundle/Exception/error404.html.twig', $response->getContent());

$request = Request::create('/hidden/system/error/other');
$response = $kernel->handle($request, HttpKernelInterface::MAIN_REQUEST, false);
file_put_contents('/app/backend/templates/bundles/TwigBundle/Exception/error.html.twig', $response->getContent());
// далее согласно документации 404 и другие исключения будут рендериться используя данные файлы
// https://symfony.com/doc/6.4/controller/error_pages.html

Для поиска: console controller action call or execute action of controller with console


11.09.2021 07:08

Комментарии

Комментариев пока нет.


Copyrights © 2007 - 2026 YaPro.Ru