telekommander
9/30/2016 - 12:42 PM

Slim 3.* automatic path ( /controller/method ) to Class::method mapping.

Slim 3.* automatic path ( /controller/method ) to Class::method mapping.

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->get('/[{path:.*}]', function(Request $request, Response $response, $args) {
    $path = $args ? explode('/', $args['path']) : [];

    $prefix = $this['config']->controller_prefix;
    $suffix = $this['config']->controller_suffix;

    $class  = (!empty($path)) ? $prefix.ucfirst(array_shift($path)).$suffix : $prefix.$this['config']->index_controller;
    $method = (!empty($path)) ? strtolower(array_shift($path)) : 'index';
    $method = ($method === '') ? 'index' : $method;

    if(class_exists($class) AND method_exists($class, $method)) {
        $controller = new $class($this);
        return call_user_func_array([$controller, $method], [$request, $response, $path]);
    } else {
        $not_found = $this['notFoundHandler'];
        return $not_found($request, $response, $args);
    }
});