Trigger Pimcore class rebuild from controller

Tom Hatzer • January 14, 2021

pimcore

It's pretty easy to call CLI commands from within your Pimcore controllers. In my case I wanted to rebuild the Pimcore data object classes after deploying to a system where I had no SSH access to.

This was done with a class that looked something like this:

<?php

namespace AppBundle\Controller;

use Exception;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;

class ClassRebuildController extends BaseController
{
    /**
     * @param Request $request
     * @param KernelInterface $kernel
     * @param string|null $key
     * @return Response
     *
     * @throws Exception
     */
    public function rebuildAction(Request $request, KernelInterface $kernel, ?string $key): Response
    {
        $application = new Application($kernel);
        $application->setAutoExit(false);

        $args = [
            'command' => 'pimcore:deployment:classes-rebuild',
            // '-q' // remove the comment at the start of the line to suppress command output
        ];

        $input = new ArrayInput($args);

        // You can use NullOutput() if you don't need the output
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $content = $output->fetch();

        // return new Response(""), if you used NullOutput()
        return new Response($content);
    }
}

You then just need to add this controller action to your routes configuration file and possibly add a check to allow only users with permission to execute the action.