Understanding Slim 4 routing function

Viewed 15

I am trying to learn slim framework and I am following the tutorial. What I would like is a detailed explanation of what the be low snippet of code is doing within the slim environment.

$app->get('/client/{name}'

The reason that I am asking is because in keep getting route not found. But I have yet to figure out why. The base route works. But when I added the twig and tried to route to that. It fails.

Now comes the code: This part is in my webroot/public/index.php

<?php

use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\Error\LoaderError;


require __DIR__ . '/../vendor/autoload.php';

$container = new Container;

$settings = require __DIR__ . '/../app/settings.php';
$settings($container);

AppFactory::setContainer($container);
$app = AppFactory::create();

$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);

// Create Twig
$twigPath = __DIR__ . "/../templates";
$twig = '';
try {
    $twig = Twig::create($twigPath, ['cache' => false]);
} catch (LoaderError $e) {
    echo "Error " . $e->getMessage();
}

// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));

$routes = require __DIR__ . '/../app/routes.php';

$routes($app);

$app->run();

This part is in the routes.php:

<?php

use Slim\App;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\Twig;


return function (App $app) {

    $app->get('/', function (Request $request, Response $response, array $args) {
        $response->getBody()->write("Hello world! Really?");
        return $response;
    });

    $app->get('/client/{name}', function (Request $request, Response $response, $args) {
        $view = Twig::fromRequest($request);
        return $view->render($response, 'client_profiles.html', [
            'name' => $args['name']
        ]);
    })->setName('profile');
};

The first route works fine the second does not. According to what I am reading. It should work. https://www.slimframework.com/docs/v4/features/templates.html

I feel that if I knew what get is looking to do. I may be able to fix it and build a proper route.

When I dig into the $app->get which connects with the RouterCollecorProxy.php. There is the $pattern variable and $callable. The callable is the anonymous function that comes after the common in the

$app->get('/client/{name}', function <- this is the callable, right?

I see the map class which takes me to the createRoute which returns the $methods, $pattern, callable and a few other things.

I think the pattern is where my problem is.

0 Answers
Related