【问题标题】:how to adding error handler in slim3 middleware如何在 slim3 中间件中添加错误处理程序
【发布时间】:2016-06-30 12:22:22
【问题描述】:

我用 slim3 框架开始了一个项目。在我的项目中,我为管理员编写了一个名为 admin 的路由组。

$app->group('/admin', function () use ($app) {
    $app->add( new AdminMiddleWare() );
    $app->get('/books/{id}', function ($request, $response, $args) {
        ...
    });
});

任何管理员都应该发送一个 GET 令牌进行验证。 我想创建一个中间件来检查管理员令牌,如果令牌未设置或无效,则显示 403 错误。

中间件类:

class AdminMiddleWare
{
    /**
     * Example middleware invokable class
     *
     * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
     * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
     * @param  callable                                 $next     Next middleware
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function __invoke($request, $response, $next)
    {
        ???
    }
}

你能帮帮我吗?

【问题讨论】:

    标签: slim middleware slim-3


    【解决方案1】:

    首先,您可以对添加中间件的方式进行小幅改进。

    $app->group('/admin', function () use ($app) {
        $app->get('/books/{id}', function ($request, $response, $args) {
            ...
        });
    })->add( new AdminMiddleWare() );
    

    将中间件附加到组而不是整个应用程序。

    至于您的问题,您将在请求对象中获得查询参数。 即对于像 example.com/admin/books/12?token=sf342ad 这样的 URL,您将拥有 $params['token'] == 'sf342ad'

    public function __invoke($request, $response, $next)
    {
        $params = $request->getQueryParams();
    }
    

    将令牌添加为路由的一部分可能会更容易,因为您可以使用反向路由生成 URL:

    $app->group('/admin/{token}', function () use ($app) {
        $app->get('/books/{id}', function ($request, $response, $args) {
            ...
        })->setName('admin-book');
    });
    

    通过这样做,您将在 $args 数组中拥有一个 token 键,它将匹配诸如 example.com/admin/sf342ad/books/1 之类的 URL

    您可以稍后构建路线而无需进行太多硬编码:

    $app->getContainer()->get('router')->pathFor('admin-book', ['token' =>'your token', 'id' => 'book id'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 2020-11-05
      • 2012-02-09
      相关资源
      最近更新 更多