How can i create middleware on Slim Framework 3?

2019-02-21 05:35发布

问题:

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)



标签: php slim slim-3