只想简单的做个带几个路由的服务,用 PHP 框架就有点大题小作了。Klein.php,这个轻量级的路由库,此时是一个不错的选择。
简介
Klein.php,是 klein 组织在 Github 上开源的 PHP 路由库,代码仓库在 ,目前版本为 2.1.2。Klein 十分灵活, 使用正则表达式 进行路由匹配;接口简单,方便快速上手开发;性能优秀,每秒可处理 2500+ 请求。
安装
Klein 需要 PHP 5.3.x,使用 Composer 进行安装:
php composer.phar require klein/klein
并在主 PHP 文件中加入 autoload:
require 'vendor/autoload.php';
示例
Klein 的使用十分简单,以下是一个 Hello World 例子:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$klein = new KleinKlein();
$klein->respond('GET', '/hello-world', function () {
return 'Hello World!';
});
$klein->dispatch();
使用 respond 注册路由处理方法,并使用 dispatch 运行路由。
Klein 对于路由匹配使用可带命名参数的正则表达式进行,而解析得到的参数可以通过 $ request 参数获得:
$klein->respond('/[:name]', function ($request) {
return 'Hello ' . $request->name;
});
下面再看一些更加复杂的例子:
/posts/[*:title][i:id] // 匹配 /posts/this-is-a-title-123
/ output .[xml| json :format]? // 匹配 /output,/output.xml 和 /output.json
/[: controller ]?/[:action]? // 匹配可选的 /controller/action 格式
也可以同时匹配多种请求方法,通过传递 array 实现:
$klein->respond(array('POST','GET'), $route, $callback);
对于文件上传,klein 通过回调的 $ service 参数接收;而对于发送文件,则可以使用 $response 的 send 或 file 实现:
$klein->respond(function ($request, $response, $service) {
$service->xml = function ($object) {
// 处理XML文件
}
$service-> csv = function ($object) {
// 处理CSV文件
}
});
$klein->respond('/report.[xml|csv|json:format]?', function ($request, $response, $service) {
$send = $request->param('format', 'json');
$response->$send($report); // 通过send返回对象
});
$klein->respond('/report/latest', function ($request, $response, $service) {
$response->file('/ tmp /cached_report.zip'); // 通过file返回文件路径的文件
});
更多
- Klein 支持路由组,可以在同一路由下定义不同的子路由以形成不同的路由命名空间。
$klein->with('/users', function () use ($klein) {
$klein->respond('GET', '/?', function ($request, $response) {
// 用户列表
});
$klein->respond('GET', '/[:id]', function ($request, $response) {
// 获取单个用户
});
});
- Klein 支持服务的惰性存储,可以在首次使用时才初始化。
- Klein 支持参数验证,可自定义验证方法。
$service-> validate Param('key')->isHex();
$service->validate($username)->isLen(4,16);
$service->validateParam('key', 'The key was invalid')->isHex()->isLen(32);
- Klein 支持对 PHTML 的带参数渲染。
$service->render('myview.phtml', array('title' => 'My View'));
总结
Klein.php 作为一个轻量的 PHP 路由库,具备了进行微型 Web 服务应用开发的能力;其基于正则的路由匹配方法自由灵活,方便使用;接口简洁明了,易于上手使用。
Klein.php 项目结构清晰,代码注释和文档丰富,单元测试完备,同时代码量不大,代码质量较高,是一个值得学习的PHP库。
Hello to all, the contents existing at this
web page are in fact amazing for people knowledge, well, keep up the
nice work fellows.
Does your website have a contact page? I’m having problems locating it but, I’d like
to shoot you an email. I’ve got some ideas for your blog you might be interested in hearing.
Either way, great blog and I look forward
to seeing it improve over time.
Awesome article.