這個文件是針對 Slim 4。正在尋找 Slim 3 文件 嗎?
Slim 是個 PHP 微型架構,它能幫助您快速撰寫簡潔又有力的網路應用程式和 API。Slim 的核心是個接收 HTTP 請求、呼叫合適的回呼常式、並回傳一個 HTTP 回應的調度員。僅此而已。
Slim 是個建立 API 的理想工具,用以消耗、重新利用或發布資料。Slim 也是個進行快速原型製作的絕佳工具。哎呀,您甚至可以使用使用者介面來建立完整特色的網路應用程式。更重要的是,Slim 的速度非常快,而且程式碼極少。
Slim 的核心是個接收 HTTP 請求、呼叫合適的回呼常式、並回傳一個 HTTP 回應的調度員。僅此而已。
您總是需要像 Symfony 或 Laravel 這種一應俱全的解決方案嗎?這些絕對是好工具。但它們常常會過度。相反地,Slim 只提供一個能滿足您需求、但卻什麼都不做的少量工具組合。
首先,您需要一個 Nginx 或 Apache 等的網路伺服器。您應配置您的網路伺服器,以便將所有適當的請求傳送至一個「前端控制器」PHP 檔。您會在這個 PHP 檔中實例化並執行您的 Slim 應用程式。
Slim 應用程式包含回應特定 HTTP 要求的路由。每個路由都會呼叫一個回呼函數並傳回一個 HTTP 回應。若要開始,您會先實例化並配置 Slim 應用程式。接著,您定義應用程式的路由。最後,您執行 Slim 應用程式。就是這麼簡單。以下是範例應用程式
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
/**
* Instantiate App
*
* In order for the factory to work you need to ensure you have installed
* a supported PSR-7 implementation of your choice e.g.: Slim PSR-7 and a supported
* ServerRequest creator (included with Slim PSR-7)
*/
$app = AppFactory::create();
/**
* The routing middleware should be added earlier than the ErrorMiddleware
* Otherwise exceptions thrown from it will not be handled by the middleware
*/
$app->addRoutingMiddleware();
/**
* Add Error Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* @param LoggerInterface|null $logger -> Optional PSR-3 Logger
*
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
// Run app
$app->run();
當您建立 Slim 應用程式時,您經常會直接使用 Request 和 Response 物件。這些物件代表網路伺服器收到的實際 HTTP 請求和最終傳回給客戶端的 HTTP 回應。
每個 Slim 應用程式路由都會將目前的 Request 和 Response 物件作為引數傳遞給其回呼常式。這些物件實作熱門的 PSR-7 介面。Slim 應用程式路由可以視需要檢查或操作這些物件。最終,每個 Slim 應用程式路由一定要傳回一個 PSR-7 Response 物件。
Slim 設計為也可以順利與其他 PHP 元件互動。您可以註冊其他第一方元件,例如 Slim-Csrf、Slim-HttpCache 或 Slim-Flash,而這些元件都是建立在 Slim 的預設功能之上。您也可以輕鬆整合在 Packagist 上找到的第三方元件。
如果您是 Slim 新手,我建議您從頭到尾閱讀此文件。如果您已經熟悉 Slim,您可以直接跳到適當的章節。
此文件會從說明 Slim 的概念和架構開始,然後再深入探討特定主題,例如要求和回應處理、路由和錯誤處理。
本網站和文件以 創意共用 署名-非商業性使用-禁止改作 4.0 國際授權 授權。