【问题标题】:How can i create middleware on Slim Framework 3?如何在 Slim Framework 3 上创建中间件?
【发布时间】:2017-06-18 06:35:53
【问题描述】:

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

在 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 下做了这个,但我想为此创建类或中间件。我能怎么做?我必须使用哪个文件夹或文件。

【问题讨论】:

  • 中间件怎么样?您是否正在寻找制作控制器? slimframework.com/docs/objects/…。至于问题,您可以制作任何您想要的中间件文件夹和有意义的文件。
  • 好的。我想做类 HomeController 。我可以在哪里创建 HomeController.php? (src在哪个文件夹下?)
  • src/Controller 应该不错。
  • 你可以把文件放在你想放的任何地方。

标签: php slim slim-3


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2021-05-31
    • 2017-04-08
    • 1970-01-01
    相关资源
    最近更新 更多