Reputation: 45
My situation: I have a NavigatorController which is triggered by AJAX requests, and will
$this->forward("controllername")
the request. But how can I check if the controller exists based on controller name? Of course, BEFORE the actual forward happens and throws an error when the page controller does not exists.
Upvotes: 4
Views: 1615
Reputation: 2654
Also You can check by using 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";
}
}
Upvotes: 2
Reputation: 1408
You can actually use the controller_resolver service that Symfony uses in order to check if controller exists.
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 it helps!
Upvotes: 6