最简单粗暴和直接的方法——到github下载zip文件,slim github【链接】。解压之后把【1】Slim文件夹,【2】.htaccess文件和【3】index.php文件复制到www目录中。若看到以下网页说明slim安装成功。

b37eb687929ec57cb8bcde106f8d0417.png

图2 slim安装成功

4.简单的修改和测试

Slim提供完善的REST框架,支持GET、POST、PUT和Delete等方法,可以把index.php修改的更简单一些。可从以下代码中可以熟悉Slim的基本框架和使用方法。

[php] view

plaincopy

/**

* 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方法也类似。

326169ec8ffa29cc05bdce4b5a01bb02.png

图3 Slim Get路由

其他类型的测试方法可借助cURL工具

【1】测试post

curl --request POSThttp://localhost/post

【2】测试put方法

curl --request PUThttp://localhost/put

【3】测试delete

curl --request DELETEhttp://localhost/delete

【火狐浏览器】

如果你不喜欢使用curl工具,也可以选择火狐浏览器中的HTTPRequest工具,那么命令操作就成了愉快的GUI操作了。

f9d0a8f10fce00b36442aaa02856d34d.png

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐