-2

我在这里阅读了有关创建中间件的文档。但是我必须创建哪个文件夹或文件?文档不包含此信息。

在我的 src 文件夹下middleware.php

例如,我想获得这样的帖子信息:

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

我在routes.php下做了这个,但我想为此创建类或中间件。我能怎么做?我必须使用哪个文件夹或文件。

4

1 回答 1

1

Slim3 不会将您绑定到特定的文件夹结构,但它确实(而是)假设您使用 composer 并使用 PSR 文件夹结构之一。

就个人而言,这就是我使用的(嗯,一个简化版本):

在我的索引文件 /www/index.php 中:

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

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

在 /src/My/Slim/Application.php 中:

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

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

    }
}

我在 DI/services.php 中定义了所有依赖注入,在 config/slim-routes.php 中定义了所有路由定义。请注意,由于我在 Application 构造函数中包含路由,因此它们将 $this 引用包含文件中的应用程序。

然后在 DI/services.php 你可以有类似的东西

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

在 config/slim-routes.php 类似

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

最后是你的控制器 /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');
    }
}

此外,返回 json 的最佳方式是使用return $response->withJson($toReturn)

于 2017-02-03T10:52:28.807 回答