You could add that logic to a ControllerBase:
class ControllerBase extends Phalcon\Mvc\Controller
{
protected function checkAjaxRequired()
{
if (!$this->request->isAjax()) {
$this->response->setStatusCode(404, "Not Found");
$this->dispatcher->forward(array(
'controller' => 'error',
'action' => '_404',
));
return false;
}
return true;
}
}
Then check if in specific actions:
class ProductsController extends ControllerBase
{
public function saveAction()
{
if ($this->checkAjaxRequired()) {
//...
}
}
}
Another option is create a plugin that check for methods marked with an annotation:
class ProductsController extends Phalcon\Mvc\Controller
{
/**
* @RequireAjax
*/
public function saveAction()
{
//...
}
}
<?php
class CheckAjaxPlugin extends \Phalcon\Mvc\User\Plugin
{
public function beforeExecuteRoute($event, $dispatcher)
{
$annotations = $this->annotations->getMethod(
$dispatcher->getActiveController(),
$dispatcher->getActiveMethod()
);
//Check if the method has an annotation 'RequireAjax'
if ($annotations->has('RequireAjax')) {
if (!$this->request->isAjax()) {
$this->response->setStatusCode(404, "Not Found");
$this->dispatcher->forward(array(
'controller' => 'error',
'action' => '_404',
));
return false;
}
}
return true;
}
}