<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # 中間件 ***** 您可以在Slim應用程序 **before** 和 **after** 運行代碼,以根據需要操作請求和響應對象。這稱為中間件。你為什么要這么做?也許你想保護你的應用程序不被跨站請求偽造。也許您想在應用程序運行之前驗證請求。中間件非常適合這些場景。 You can run code*before*and*after*your Slim application to manipulate the Request and Response objects as you see fit. This is called*middleware*. Why would you want to do this? Perhaps you want to protect your app from cross-site request forgery. Maybe you want to authenticate requests before your app runs. Middleware is perfect for these scenarios. ## 什么是中間件? 中間件實現了 [PSR-15 Middleware Interface](https://www.php-fig.org/psr/psr-15/): 1. `Psr\Http\Message\ServerRequestInterface`\- The PSR-7 request object 2. `Psr\Http\Server\RequestHandlerInterface`\- The PSR-15 request handler object 它可以對這些對象做任何適當的事情。唯一的硬性要求是中間件**必須**返回一個`Psr\Http\Message\ResponseInterface`實例。每個中間件都**應該**調用下一個中間件,并將請求和響應對象作為參數傳遞給它。 It can do whatever is appropriate with these objects. The only hard requirement is that a middleware**MUST**return an instance of`Psr\Http\Message\ResponseInterface`. Each middleware**SHOULD**invoke the next middleware and pass it Request and Response objects as arguments. ## 中間件如何工作? Different frameworks use middleware differently. Slim adds middleware as concentric layers surrounding your core application. Each new middleware layer surrounds any existing middleware layers. The concentric structure expands outwardly as additional middleware layers are added. > 不同的框架以不同的方式使用中間件。Slim將中間件作為圍繞核心應用程序的同心層添加。每個新的中間件層都圍繞著任何現有的中間件層。隨著附加的中間件層的添加,同心結構向外擴展。 The last middleware layer added is the first to be executed. > 最后添加的中間件層是要執行的第一個層。 When you run the Slim application, the Request object traverses the middleware structure from the outside in. They first enter the outer-most middleware, then the next outer-most middleware, (and so on), until they ultimately arrive at the Slim application itself. After the Slim application dispatches the appropriate route, the resultant Response object exits the Slim application and traverses the middleware structure from the inside out. Ultimately, a final Response object exits the outer-most middleware, is serialized into a raw HTTP response, and is returned to the HTTP client. Here’s a diagram that illustrates the middleware process flow: > 當您運行Slim應用程序時,請求對象從外向內遍歷中間件結構。它們首先進入最外面的中間件,然后進入下一個最外面的中間件(等等),直到最終到達Slim應用程序本身。Slim應用程序分派適當的路由后,生成的響應對象退出Slim應用程序并從內到外遍歷中間件結構。最終,最終的響應對象退出最外層的中間件,序列化為原始的HTTP響應,然后返回給HTTP客戶端。下圖展示了中間件流程流: ![](https://box.kancloud.cn/2015-10-23_5629d1b6da0db.png) ## 如何編寫中間件? Middleware is a callable that accepts two arguments: a`Request`object and a`RequestHandler`object. Each middleware**MUST**return an instance of`Psr\Http\Message\ResponseInterface`. > 中間件是一個可調用的,它接受兩個參數: > > 一個`Request`對象和一個`RequestHandler`對象。 > > 每個中間件**必須**返回一個`Psr\Http\Message\ResponseInterface`的實例。 ## 關閉中間件的例子。 > 這個示例中間件是一個閉包。 ~~~php <?php use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Factory\AppFactory; use Slim\Psr7\Response; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); /` * Example middleware closure * * @param ServerRequest $request PSR-7 request * @param RequestHandler $handler PSR-15 request handler * * @return Response */ $beforeMiddleware = function (Request $request, RequestHandler $handler) { $response = $handler->handle($request); $existingContent = (string) $response->getBody(); $response = new Response(); $response->getBody()->write('BEFORE' . $existingContent); return $response; }; $afterMiddleware = function ($request, $handler) { $response = $handler->handle($request); $response->getBody()->write('AFTER'); return $response; }; $app->add($beforeMiddleware); $app->add($afterMiddleware); // ... $app->run(); ~~~ ## 調用類中間件的例子 This example middleware is an invokable class that implements the magic`__invoke()`method. > 這個示例中間件是一個可調用的類,它實現了神奇的 **invoke()** 方法。 ~~~php <?php use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Psr7\Response; class ExampleBeforeMiddleware { /** * Example middleware invokable class * * @param ServerRequest $request PSR-7 request * @param RequestHandler $handler PSR-15 request handler * * @return Response */ public function __invoke(Request $request, RequestHandler $handler): Response { $response = $handler->handle($request); $existingContent = (string) $response->getBody(); $response = new Response(); $response->getBody()->write('BEFORE' . $existingContent); return $response; } } ~~~ ~~~php <?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; class ExampleAfterMiddleware { /** * Example middleware invokable class * * @param ServerRequest $request PSR-7 request * @param RequestHandler $handler PSR-15 request handler * * @return Response */ public function __invoke(Request $request, RequestHandler $handler): Response { $response = $handler->handle($request); $response->getBody()->write('AFTER'); return $response; } } ~~~ To use these classes as a middleware, you can use**add(new ExampleMiddleware());**function chain after the**$app**route mapping methods**get(), post(), put(), patch(), delete(), options(), any()**or**group()**, which in the code below, any one of these, could represent $subject. > 要將這些類用作中間件,可以使用`add(new ExampleMiddleware())`; > > $app路由映射方法`get()`、`post()`、`put()`、`patch()`、`delete()`、`options()`、`any()`或`group()`之后的函數鏈,在下面的代碼中,這些方法中的任何一個都可以表示`$subject`。 ~~~php <?php use Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); // Add Middleware On App $app->add(new ExampleMiddleware()); // Add Middleware On Route $app->get('/', function () { ... })->add(new ExampleMiddleware()); // Add Middleware On Group $app->group('/', function () { ... })->add(new ExampleMiddleware()); // ... $app->run(); ~~~ ## 如何添加中間件? You may add middleware to a Slim application, to an individual Slim application route or to a route group. All scenarios accept the same middleware and implement the same middleware interface. > 可以向Slim應用程序、單個Slim應用程序路由或路由組添加中間件。 > > 所有場景都接受相同的中間件并實現相同的中間件接口。 ## 應用程序中間件 Application middleware is invoked for every**incoming**HTTP request. Add application middleware with the Slim application instance’s **add()** method. This example adds the Closure middleware example above: > 為每個**傳入**的HTTP請求調用應用程序中間件。 > > 使用Slim應用程序實例的`add()`方法的應用程序中間件。 > > 這個例子添加了上面的閉包中間件例子: ~~~php <?php use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Factory\AppFactory; use Slim\Psr7\Response; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $app->add(function (Request $request, RequestHandler $handler) { $response = $handler->handle($request); $existingContent = (string) $response->getBody(); $response = new Response(); $response->getBody()->write('BEFORE ' . $existingContent); return $response; }); $app->add(function (Request $request, RequestHandler $handler) { $response = $handler->handle($request); $response->getBody()->write(' AFTER'); return $response; }); $app->get('/', function (Request $request, Response $response, $args) { $response->getBody()->write('Hello World'); return $response; }); $app->run(); ~~~ ``` 這將輸出這個HTTP響應體: ``` ~~~bash BEFORE Hello World AFTER ~~~ ## 路由中間件 Route middleware is invoked*only if*its route matches the current HTTP request method and URI. Route middleware is specified immediately after you invoke any of the Slim application’s routing methods (e.g.,**get()**or**post()**). Each routing method returns an instance of **\Slim\Route** , and this class provides the same middleware interface as the Slim application instance. Add middleware to a Route with the Route instance’s **add()** method. This example adds the Closure middleware example above: > 路由中間件 *只有* 在其路由與當前HTTP請求方法和URI匹配時才會被調用。 > > 路由中間件是在您調用任何Slim應用程序的路由方法(例如,**get()**或**post()**)后立即指定的。 > > 每個路由方法返回一個`\Slim\Route`實例,該類提供與Slim應用程序實例相同的中間件接口。 > > 使用路由實例的 **Add()** 方法向路由添加中間件。 > > 這個例子添加了上面的閉包中間件例子: ~~~php <?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $mw = function (Request $request, RequestHandler $handler) { $response = $handler->handle($request); $response->getBody()->write('World'); return $response; }; $app->get('/', function (Request $request, Response $response, $args) { $response->getBody()->write('Hello '); return $response; })->add($mw); $app->run(); ~~~ 這將輸出這個HTTP響應體: ~~~bash Hello World ~~~ ## 組中間件 In addition to the overall application, and standard routes being able to accept middleware, the **group()** multi-route definition functionality, also allows individual routes internally. Route group middleware is invoked*only if*its route matches one of the defined HTTP request methods and URIs from the group. To add middleware within the callback, and entire-group middleware to be set by chaining **add()** after the **group()** method. > 除了整個應用程序和能夠接受中間件的標準路由之外, **group()** 多路由定義功能還允許內部使用單個路由。 > > *只有*當路由組中間件的路由與組中定義的HTTP請求方法和uri之一匹配時,才會調用路由組中間件。 > > 在回調中添加中間件,并在 **group()** 方法之后通過鏈接 **add()** 設置實體組中間件。 Sample Application, making use of callback middleware on a group of url-handlers > 示例應用程序,利用一組url處理程序上的回調中間件 ~~~php <?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Server\RequestHandlerInterface as RequestHandler; use Slim\Factory\AppFactory; use Slim\Routing\RouteCollectorProxy; require __DIR__ . '/../vendor/autoload.php'; $app = AppFactory::create(); $app->get('/', function (Request $request, Response $response) { return $response->getBody()->write('Hello World'); }); $app->group('/utils', function (RouteCollectorProxy $group) { $group->get('/date', function (Request $request, Response $response) { $response->getBody()->write(date('Y-m-d H:i:s')); return $response; }); $group->get('/time', function (Request $request, Response $response) { $response->getBody()->write((string)time()); return $response; }); })->add(function (Request $request, RequestHandler $handler) use ($app) { $response = $handler->handle($request); $dateOrTime = (string) $response->getBody(); $response = $app->getResponseFactory()->createResponse(); $response->getBody()->write('It is now ' . $dateOrTime . '. Enjoy!'); return $response; }); $app->run(); ~~~ 當調用`/utils/date`方法時,將輸出類似于下面的字符串 ~~~bash It is now 2015-07-06 03:11:01. Enjoy! ~~~ 訪問`/utils/time`將輸出類似于下面的字符串 ~~~bash It is now 1436148762. Enjoy! ~~~ But visiting `/` (domain-root) , would be expected to generate the following output as no middleware has been assigned 但是,由于沒有分配任何中間件,因此訪問`/`(域-根)將生成以下輸出 ~~~bash Hello World ~~~ ## 從中間件傳遞變量 The easiest way to pass attributes from middleware is to use the request’s attributes. > 從中間件傳遞屬性的最簡單方法是使用請求的屬性。 Setting the variable in the middleware: > 在中間件中設置變量: ~~~php $request = $request->withAttribute('foo', 'bar'); ~~~ 獲取路由回調中的變量: ~~~php $foo = $request->getAttribute('foo'); ~~~ ## 尋找可用的中間件 > 您可能會發現已經編寫了滿足您需要的PSR-15中間件類。以下是一些可以搜索的非官方列表。 * [Middleware for Slim Framework v4.x wiki](https://github.com/slimphp/Slim/wiki/Middleware-for-Slim-Framework-v4.x) * [middlewares/awesome-psr15-middlewares](https://github.com/middlewares/awesome-psr15-middlewares)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看