paveldanilin/slimcontroller

This package is abandoned and no longer maintained. No replacement package was suggested.

FrontController pattern

0.1 2017-09-05 00:10 UTC

This package is auto-updated.

Last update: 2020-08-16 10:15:08 UTC


README

The implementation of FrontController pattern.

Depends on PSR interfaces:

  • Psr\Container\ContainerInterface
  • Psr\Http\Message\ServerRequestInterface
  • Psr\Http\Message\ResponseInterface

Usage

Slim3

routes

$app->group('/v1', function() {
  $this->group('/system', function() {
    $this->map(['GET', 'POST', 'PUT', 'DELETE'], '/{controller}/{action}[/{params:.*}]', 'SystemFrontController:handle');
  });
});

container

$container['SystemFrontController'] = function($c) {
  $settings = $c->get('settings')['systemFrontController'];
  return new Slim\Controller\FrontController([
    'startup_path' => '/site/controllers/',
    'namespace' => 'MyApp\\Controllers\\',
    'has_own_folder' => true,
    'route_key_controller' => 'controller',
    'route_key_action' => 'action',
    'route_key_exparams' => 'params',
    'on' => [
      'beforeControllerCall' => function($controller, $action, $request, $response, $args, $c) {
         $logger = $c->get('logger');
         $logger->info("container=$controller; action=$action; args=" . print_r($args, true));
      }
    ]
  ], $c);
};

Example

Let's assume we got GET request with URL 'http://site.com/v1/system/auth/login'. According to route settings (was described above), this request will be handled by: 'Auth' controller and 'Login' action. This controller must be located in file '/site/controllers/Auth/AuthController.php', and must be declared as AuthController class with public method login($request, $response, $args). A Container object will be injected into class constructor, hence you can get access to all services of an application within controller.

namespace MyApp\Controllers;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class AuthController 
{
    public function __construct(ContainerInterface $container) {
    }
    
    public function login(ServerRequestInterface $request, ResponseInterface $response, $args) {
        return $response;
    }
}