I was playing with the Slim framework and saw that for each action inside each controller, I had to duplicate stuff inside my router configuration.
I wanted a more “dynamic” approach, so I came up with the following.
I want to know if I overlooked something
Inside routers
(This is where only the controllers are registered)
$app->any('/admin[/{args:.*}]', function ($request, $response, $args) {
$controller = new AdminController($this, $request, $response);
return $controller->handle($args);
});
$app->any('/help[/{args:.*}]', function ($request, $response, $args) {
$controller = new HelpController($this, $request, $response);
return $controller->handle($args);
});
$app->any('[/{args:.*}]', function ($request, $response, $args) {
$controller = new FrontendIndexController($this, $request, $response);
return $controller->handle($args);
});
inside AdminController
(This is an example controller, with only the actions)
class AdminController extends BaseController
{
/**
* Return the page: index
*/
public function index()
{
return $this->view->render($this->response, $this->templateDir . '/index.twig', []);
}
/**
* Return the page: page2
*/
public function page2($args)
{
return $this->view->render($this->response, $this->templateDir . '/page2.twig', []);
}
}
inside BaseController
(This is where the “dynamic” part is)
/**
* Handles the routing inside the controller
*
* @param $args - all url arguments
*/
public function handle($args)
{
$args = $this->getArgs($args);
if (empty($args[0]))
{
$this->index();
}
else
{
try
{
$this->{$args[0]}(...$args);
}
catch (\Error $e)
{
$this->error($e->getMessage());
}
}
}
private function getArgs($args)
{
if (!empty($args))
{
$args = explode("/", $args['args']);
}
return $args;
}
private function error($message, $args)
{
echo 'Error:<BR>' . $message. '<HR>';
var_dump($args);
}