最簡單粗暴和直接的方法——到github下載zip檔案,slim github【連結】。解壓之後把【1】Slim檔案夾,【2】.htaccess檔案和【3】index.php檔案複製到www目錄中。若看到以下網頁說明slim安裝成功。
圖2 slim安裝成功
4.簡單的修改和測試
Slim提供完善的REST架構,支援GET、POST、PUT和Delete等方法,可以把index.php修改的更簡單一些。可從以下代碼中可以熟悉Slim的基本架構和使用方法。
[php] view plain copy
<?php /** * Step 1: Require the Slim Framework * * If you are not using Composer, you need to require the * Slim Framework and register its PSR-0 autoloader. * * If you are using Composer, you can skip this step. */ require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader(); /** * Step 2: Instantiate a Slim application * * This example instantiates a Slim application using * its default settings. However, you will usually configure * your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new \Slim\Slim(); /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ // GET route $app->get( '/', function () { echo 'Hello Slim'; } ); // POST route $app->post( '/post', function () { echo 'This is a POST route'; } ); // PUT route $app->put( '/put', function () { echo 'This is a PUT route'; } ); // PATCH route $app->patch('/patch', function () { echo 'This is a PATCH route'; }); // DELETE route $app->delete( '/delete', function () { echo 'This is a DELETE route'; } ); /** * Step 4: Run the Slim application * * This method should be called last. This executes the Slim application * and returns the HTTP response to the HTTP client. */ $app->run(); 此時再開啟瀏覽器輸入localhost將只能看到以下內容,其實瀏覽器使用get方法,在slim的Get路由中輸出了Hello Slim。 $app->post( '/post', function () { echo 'This is a POST route'; } );
在slim中, '/post'為相對路徑,該路徑可支援變數。 function ()為後續的處理函數。其他HTTP方法也類似。
圖3 Slim Get路由
其他類型的測試方法可藉助cURL工具
【1】測試post
curl --request POST http://localhost/post
【2】測試put方法
curl --request PUT http://localhost/put
【3】測試delete
curl --request DELETE http://localhost/delete
【Firefox瀏覽器】
如果你不喜歡使用curl工具,也可以選擇Firefox瀏覽器中的HTTPRequest工具,那麼命令操作就成了愉快的GUI操作了。