How can i create middleware on Slim Framework 3?

为君一笑 提交于 2019-12-01 14:53:29

Slim3 does not tie you to a particular folder structure, but it does (rather) assume you use composer and use one of the PSR folder structures.

Personally, that's what I use (well, a simplified version):

in my index file /www/index.php:

include_once '../vendor/autoload.php';

$app = new \My\Slim\Application(include '../DI/services.php', '../config/slim-routes.php');
$app->run();

In /src/My/Slim/Application.php:

class Application extends \Slim\App
{
    function __construct($container, $routePath)
    {
        parent::__construct($container);

        include $routePath;
        $this->add(new ExampleMiddleWareToBeUsedGlobally());

    }
}

I define all the dependency injections in DI/services.php and all the route definitions in config/slim-routes.php. Note that since I include the routes inside the Application constructor, they will have $this refer to the application inside the include file.

Then in DI/services.php you can have something like

$container = new \Slim\Container();
$container['HomeController'] = function ($container) {
    return new \My\Slim\Controller\HomeController();
};
return $container;

in config/slim-routes.php something like

$this->get('/', 'HomeController:showHome'); //note the use of $this here, it refers to the Application class as stated above

and finally your controller /src/My/Slim/Controller/HomeController.php

class HomeController extends \My\Slim\Controller\AbstractController
{
    function showHome(ServerRequestInterface $request, ResponseInterface $response)
    {
        return $response->getBody()->write('hello world');
    }
}

Also, the best way to return json is with return $response->withJson($toReturn)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!