Slim Cheatsheet

Sample Application

<?php
// Create and configure Slim app
$app = new \Slim\App;

// Define app routes
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello " . $args['name']);
});

// Run app
$app->run();

PSR7

Slim supports PSR-7 interfaces for its Request and Response objects

Middleware

Middleware is code that runs before and after your Slim application.

Dependency Container

$container = new \Slim\Container;
$app = new \Slim\App($container);

Routes

$app->any( '/toolkit/{option}', '\Controllers\MyController:getIndex' );

To retrieve {option}

public function getIndex(Request $request, Response $response, $args) {
    ...
    $option = $args['option'];
    ...

Request Object

Query parameters

If your endpoint is /url?keywords=helloworld you would retrieve keywords:

$allGetVars = $request->getQueryParams()
$keywords = $allGetVars['keywords'];

Post (or PUT) parameters

$allPostPutVars = $request->getParsedBody();
$keywords = $allPostPutVars['keywords'];

or

$request->getParam('keywords');

Response Object

Redirect return $response->withRedirect('/404');

Templates

Views

path_for(route,route placeholder names and value)

    <a href="{{ path_for('profile', { 'name': 'josh' }) }}">Josh</a>

Retrieving Current Route

$route = $request->getAttribute('route');
$name = $route->getName();
$group = $route->getGroup();
$methods = $route->getMethods();
$arguments = $route->getArguments();

Retrieving Current IP address

Use Middleware package https://github.com/akrabat/rka-ip-address-middleware

$container = new \Slim\Container;
$app = new \Slim\App($container);

// register middleware

$checkProxyHeaders = true;
$trustedProxies = ['10.0.0.1', '10.0.0.2'];
$app->add(new RKA\Middleware\IpAddress($checkProxyHeaders, $trustedProxies));

Twig

Cache

Enabling

$view = new \Slim\Views\Twig('../app/templates', [
        'cache' => '../storage/cache'
    ]);

Disabling

$view = new \Slim\Views\Twig('../app/templates', [
        'cache' => null
    ]);

Extend a layout

{% extends "layout.html" %}

Blocks

{% block content %}

...

{% endblock %}

Parse Raw

If your variable has html in it for example, you can tell Twig not to escape this:

{{ item.htmldata() | raw }}

Foreach

 {% for item in posts %}

 {% endfor %}

404 pages

Add to container before calling $app->run();

//Override the default Not Found Handler
$container['notFoundHandler'] = function ($c) {
        return function ($request, $response) use ($c) {
                return $c['view']->render($response, '404.html', [
                        "myMagic" => "Let's roll"
                ]);
        };
};

Note make sure you add container when initiating app $app = new \Slim\App($container);

Thanks