企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 路由回调 Each routing method described above accepts a callback routine as its final argument. This argument can be any PHP callable, and by default it accepts three arguments. > 上面描述的每个路由方法都接受一个回调例程作为它的最后一个参数。这个参数可以是任何PHP可调用的,默认情况下它接受三个参数。 * `Request`The first argument is a`Psr\Http\Message\ServerRequestInterface`object that represents the current HTTP request. * `Response`The second argument is a`Psr\Http\Message\ResponseInterface`object that represents the current HTTP response. * `Arguments`The third argument is an associative array that contains values for the current route’s named placeholders. > `Request`第一个参数是一个代表当前Http请求的`Psr\Http\Message\ServerRequestInterface`对象。 > > `Response`第二个参数是一个代表当前Http响应的`Psr\Http\Message\ResponseInterface`对象。 > > `Arguments`第三个参数是一个关联数组,它包含当前路由的命名占位符的值。 ### 向响应写入内容 There are two ways you can write content to the HTTP response. First, you can simply `echo()` content from the route callback. This content will be appended to the current HTTP response object. Second, you can return a `Psr\Http\Message\ResponseInterface` object. 有两种方法可以将内容写入HTTP响应。首先,您可以简单地从路由回调`echo()`内容。此内容将附加到当前HTTP响应对象。其次,您可以返回一个`Psr\Http\Message\ResponseInterface`对象。 ### Closure binding闭包绑定 If you use a [dependency container](http://www.slimframework.com/docs/v4/concepts/di.html) and a `Closure`instance as the route callback, the closure’s state is bound to the `Container` instance. This means you will have access to the DI container instance `inside` of the Closure via the `$this` keyword: > 如果使用`依赖容器`和`闭包`实例作为路由回调,则闭包的状态绑定到`容器`实例。这意味着你可以通过`$This`关键字访问闭包内部的DI容器实例: ~~~php $app->get('/hello/{name}', function ($request, $response, $args) { // Use app HTTP cookie service $this->get('cookies')->set('name', [ 'value' => $args['name'], 'expires' => '7 days' ]); }); ~~~ **Heads Up!** Slim does not support`static`closures. > **提醒!** > Slim不支持`静态`闭包。 ## Redirect helper重定向的助手 You can add a route that redirects `GET` HTTP requests to a different URL with the Slim application’s `redirect()` method. It accepts three arguments: 1. The route pattern (with optional named placeholders) to redirect `from` 2. The location to redirect `to` , which may be a `string` or a [Psr\\Http\\Message\\UriInterface](https://www.php-fig.org/psr/psr-7/#35-psrhttpmessageuriinterface) 3. The HTTP status code to use (optional; `302` if unset) > 您可以使用Slim应用程序的`redirect()`方法添加一个将 `GET`HTTP请求重定向到另一个URL的路由。它接受三个参数: > 1. 路由模式(带有可选的命名占位符)来重定向 `from` > 2. 重定向到的位置,可以是一个 `string`或一个 [Psr\\Http\\Message\\UriInterface](https://www.php-fig.org/psr/psr-7/#35-psrhttpmessageuriinterface) > 3.要使用的HTTP状态码(可选;如果未设置的`302`) ~~~php $app->redirect('/books', '/library', 301); ~~~ `redirect()` routes respond with the status code requested and a `Location` header set to the second argument. > `redirect()`路由使用请求的状态码和设置到第二个参数的`Location`报头来响应。