How can i create middleware on Slim Framework 3?

纵然是瞬间 提交于 2019-12-01 14:24:38

问题


I read the documentation here about creating middleware. But which folder or file i must be create it? Documentation is not contain this information.

Under the src folder i have middleware.php.

For example i want to get post information like this:

$app->post('/search/{keywords}', function ($request, $response, $args) {
    $data = $request->getParsedBody();
    //Here is some codes connecting db etc...
    return json_encode($query_response);
});

i made this under the routes.php but i want to create class or middleware for this. How can i do? Which folder or file i must be use.


回答1:


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)



来源:https://stackoverflow.com/questions/41981048/how-can-i-create-middleware-on-slim-framework-3

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