最简单粗暴和直接的方法——到github下载zip文件,slim github【链接】。解压之后把【1】Slim文件夹,【2】.htaccess文件和【3】index.php文件复制到www目录中。若看到以下网页说明slim安装成功。
图2 slim安装成功
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
【火狐浏览器】
如果你不喜欢使用curl工具,也可以选择火狐浏览器中的HTTPRequest工具,那么命令操作就成了愉快的GUI操作了。
Atas ialah kandungan terperinci PHP框架slim的安装使用方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!