Symfony - check if controller exists

My situation: I have a NavigatorController that runs using AJAX requests and will

$ this-> forward ("controllername")

inquiry. But how can I check if a controller exists based on the name of the controller? Of course, BEFORE the actual busting occurs, it throws an error when the page controller does not exist.

+4
source share
2 answers

In fact, you can use the controller_resolver that Symfony uses to check for the presence of a controller.

public function indexAction(Request $request)
{
    $request->attributes->set('_controller', 'AppBundle\Controller\ExampleController::exampleAction');
    try{
        $this->get('debug.controller_resolver')->getController($request);
    } catch (\Exception $e) {
        $x = $e->getCode();
    }
}

Hope this helps!

+6
source

You can also check with Service:

namespace AppBundle\Service;

class ExampleService
{
    /**
     * @param string $controller
     * @return bool
     */
    public function has($controller)
    {
        list($class, $action) = explode('::', $controller, 2);
        return class_exists($class);
    }
}

In app/config/services.yml:

services:
    app.controller.check:
        class: AppBundle\Service\ExampleService

In Controller:

public function indexAction(Request $request)
{
    $controller = 'AppBundle\Controller\DefaultController';
    if($this->get('app.controller.check')->has($controller))
    {
        echo 'Exists';
    }
    else
    {
        echo "Doesn't exists";
    }
}
+2
source

Source: https://habr.com/ru/post/1682520/


All Articles