Saturday, October 7, 2017

Symfony 3 run console commands from controller

On shared hosting you don't have access to command line so you can use following script to clear cache:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

// Import the required classed
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;


class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        $kernel = $this->get('kernel');
        $application = new Application($kernel);
        $application->setAutoExit(false);
       
        /*
        // php bin/console doctrine:generate:entities AppBundle:Task
        $input = new ArrayInput(array(
            'command' => 'doctrine:generate:entities',
            'name' => 'AppBundle:Task'
        ));
        */
       
        // php bin/console cache:clear --env=prod --no-warmup
        $input = new ArrayInput(array(
            'command' => 'cache:clear',
            '--env' => 'prod',
            '--no-warmup' => null
        ));
       
        $output = new BufferedOutput();

        $application->run($input, $output);

        // return the output
        $content = $output->fetch();

        // Send the output of the console command as response
        return new Response($content);
    }
}

No comments:

Post a Comment