首頁  >  文章  >  後端開發  >  PHP框架slim的安裝使用方法

PHP框架slim的安裝使用方法

小云云
小云云原創
2018-03-20 11:39:317587瀏覽


最簡單粗暴直接的方法-到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 &#39;Slim/Slim.php&#39;;  
  
\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(  
    &#39;/&#39;,  
    function () {  
        echo &#39;Hello Slim&#39;;  
    }  
);  
  
// POST route  
$app->post(  
    &#39;/post&#39;,  
    function () {  
        echo &#39;This is a POST route&#39;;  
    }  
);  
  
// PUT route  
$app->put(  
    &#39;/put&#39;,  
    function () {  
        echo &#39;This is a PUT route&#39;;  
    }  
);  
  
// PATCH route  
$app->patch(&#39;/patch&#39;, function () {  
    echo &#39;This is a PATCH route&#39;;  
});  
  
// DELETE route  
$app->delete(  
    &#39;/delete&#39;,  
    function () {  
        echo &#39;This is a DELETE route&#39;;  
    }  
);  
  
/** 
 * 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(  
    &#39;/post&#39;,  
    function () {  
        echo &#39;This is a POST route&#39;;  
    }  
);

在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

#    【火狐瀏覽器】

    如果你不喜歡使用curl工具,也可以選擇火狐瀏覽器中的HTTPRequest工具,那麼命令操作就成了愉快的GUI操作了。


以上是PHP框架slim的安裝使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn