首页 >后端开发 >php教程 >PHP框架slim的安装使用方法

PHP框架slim的安装使用方法

小云云
小云云原创
2018-03-20 11:39:317706浏览


最简单粗暴和直接的方法——到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