cvele / klein.php
Requires
- php: >=5.3.2
This package is not auto-updated.
Last update: 2016-03-04 07:01:39 UTC
README
klein.php 是一个针对 PHP 5.3+ 的闪电般的路由器
- 灵活的正则表达式路由(灵感来自 Sinatra)
- 一套用于快速构建 Web 应用的 模板方法
- 几乎没有开销 => 2500+ 请求/秒
- 需要 PHP 5.3.x
- 设置 URL 重写,以便所有请求都由 index.php 处理
- 将
<?php require 'klein.php';作为第一行,将dispatch();作为最后一行 - (可选) 加一些 APC 来锦上添花
示例
示例 1 - 响应所有请求
<?php
respond(function () {
echo 'Hello World!';
});
示例 2 - 命名参数
<?php
respond('/[:name]', function ($request) {
echo 'Hello ' . $request->name;
});
示例 3 - 如此 RESTful
<?php
respond('GET', '/posts', $callback);
respond('POST', '/posts/create', $callback);
respond('PUT', '/posts/[i:id]', $callback);
respond('DELETE', '/posts/[i:id]', $callback);
// To match multiple request methods:
respond(array('POST','GET'), $route, $callback);
// Or you might want to handle the requests in the same place
respond('/posts/[create|edit:action]?/[i:id]?', function ($request, $response) {
switch ($request->action) {
//
}
});
示例 4 - 发送对象/文件
<?php
respond(function ($request, $response) {
$response->xml = function ($object) {
// Custom xml output function
}
$response->csv = function ($object) {
// Custom csv output function
}
});
respond('/report.[xml|csv|json:format]?', function ($reqest, $response) {
// Get the format or fallback to JSON as the default
$send = $request->param('format', 'json');
$response->$send($report);
});
respond('/report/latest', function ($request, $response) {
$response->file('/tmp/cached_report.zip');
});
示例 5 - 全部一起
<?php
respond(function ($request, $response, $app) {
// Handle exceptions => flash the message and redirect to the referrer
$response->onError(function ($response, $err_msg) {
$response->flash($err_msg);
$response->back();
});
// The third parameter can be used to share scope and global objects
$app->db = new PDO(...);
// $app also can store lazy services, e.g. if you don't want to
// instantiate a database connection on every response
$app->register('db', function() {
return new PDO(...);
});
});
respond('POST', '/users/[i:id]/edit', function ($request, $response) {
// Quickly validate input parameters
$request->validate('username', 'Please enter a valid username')->isLen(5, 64)->isChars('a-zA-Z0-9-');
$request->validate('password')->notNull();
$app->db->query(...); // etc.
// Add view properties and helper methods
$response->title = 'foo';
$response->escape = function ($str) {
return htmlentities($str); // Assign view helpers
};
$response->render('myview.phtml');
});
// myview.phtml:
<title><?php echo $this->escape($this->title) ?></title>
路由命名空间
<?php
with('/users', function () {
respond('GET', '/?', function ($request, $response) {
// Show all users
});
respond('GET', '/[:id]', function ($request, $response) {
// Show a single user
});
});
foreach(array('projects', 'posts') as $controller) {
with("/$controller", "controllers/$controller.php");
}
延迟服务
服务可以被存储为 延迟,这意味着它们只有在第一次使用时才会被实例化。
<?php
respond(function ($request, $response, $app) {
$app->register('lazyDb', function() {
$db = new stdClass();
$db->name = 'foo';
return $db;
});
});
//Later
respond('GET', '/posts', function ($request, $response, $app) {
// $db is initialised on first request
// all subsequent calls will use the same instance
echo $app->lazyDb->name;
});
验证器
要添加自定义验证器,请使用 addValidator($method, $callback)
<?php
addValidator('hex', function ($str) {
return preg_match('/^[0-9a-f]++$/i', $str);
});
您可以使用 is<$method>() 或 not<$method>() 验证参数,例如。
$request->validate('key')->isHex();
验证方法是可连链的,并且可以指定自定义异常消息,以在验证失败时使用
$request->validate('key', 'The key was invalid')->isHex()->isLen(32);
路由
[ match_type : param_name ]
一些示例
* // Match all request URIs
[i] // Match an integer
[i:id] // Match an integer as 'id'
[a:action] // Match alphanumeric characters as 'action'
[h:key] // Match hexadecimal characters as 'key'
[:action] // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*] // Catch all (lazy)
[*:trailing] // Catch all as 'trailing' (lazy)
[**:trailing] // Catch all (possessive - will match the rest of the URI)
.[:format]? // Match an optional parameter 'format' - a / or . before the block is also optional
更多复杂的示例
/posts/[*:title][i:id] // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]? // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]? // Matches the typical /controller/action format
注意 - 所有 与请求 URI 匹配的路由都会被调用 - 这允许您包含复杂的条件逻辑,例如用户身份验证或视图布局。例如,以下代码将包装其他路由的头和尾
respond('*', function ($request, $response) { $response->render('header.phtml'; });
//other routes
respond('*', function ($request, $response) { $response->render('footer.phtml'; });
路由自动匹配整个请求 URI。如果您需要匹配请求 URI 的部分或使用自定义正则表达式,请使用 @ 操作符。如果您需要否定路由,请使用 ! 操作符
// Match all requests that end with '.json' or '.csv'
respond('@\.(json|csv)$', ...
// Match all requests that _don't_ start with /admin
respond('!@^/admin/', ...
视图
您可以通过将它们分配给 $response 对象或将它们用作 $response->render() 的第二个参数,将属性或助手发送到视图
<?php
$response->escape = function ($str) {
return htmlentities($str);
};
$response->render('myview.phtml', array('title' => 'My View'));
// Or just: $response->title = 'My View';
myview.phtml
<title><?php echo $this->escape($this->title) ?></title>
视图是在 $response 的范围内编译和运行的,因此可以使用 $this 访问所有响应方法
<?php
$this->render('partial.html') // Render partials
$this->param('myvar') // Access request parameters
echo $this->query(array('page' => 2)) // Modify the current query string
-## API
<?php
$request->
header($key, $default = null) // Get a request header
cookie($key, $default = null) // Get a cookie from the request
session($key, $default = null) // Get a session variable
param($key, $default = null) // Get a request parameter (get, post, named)
params() // Return all parameters
params($mask = null) // Return all parameters that match the mask array - extract() friendly
validate($param, $err_msg = null) // Start a validator chain
method() // Get the request method
method($method) // Check if the request method is $method, i.e. method('post') => true
isSecure($required = false) // https? Redirect if $required is true and the request is not secure
id() // Get a unique ID for the request
ip() // Get the request IP
userAgent() // Get the request user agent
uri() // Get the request URI
<param> // Get / Set (if assigned a value)a request parameter
$response->
header($key, $value = null) // Set a response header
cookie($key, $value = null, $expiry = null) // Set a cookie
cookie($key, null) // Remove a cookie
session($key, $value = null) // Sets a session variable
flash($msg, $type = 'info', $params = array() // Set a flash message
file($path, $filename = null) // Send a file
noCache() // Tell the browser not to cache the response
json($object, $jsonp_prefix = null) // Send an object as JSON or JSONP by providing padding prefix
markdown($str, $args, ...) // Return a string formatted with markdown
code($code = null) // Return the HTTP response code, or send a new code
redirect($url, $code = 302) // Redirect to the specified URL
refresh() // Redirect to the current URL
back() // Redirect to the referer
render($view, $data = array()) // Render a view or partial (in the scope of $response)
partial($view, $data = array()) // Render a partial without a layout (in the scope of $response)
layout($layout) // Set the view layout
yield() // Call inside the layout to render the view content
error(Exception $err) // Routes an exception through the error callbacks
onError($callback) // $callback takes ($response, $msg, $err_type = null)
set($key, $value = null) // Set a view property or helper
set($arr)
escape($str) // Escape a string
query($key, $value = null) // Modify the current query string
query($arr)
param($param, $default = null) // Get an escaped request parameter
flashes($type = null) // Retrieve and clears all flashes of $type
flush() // Flush all open output buffers
discard($restart_buffer = false) // Discard all open output buffers and optionally restart it
buffer() // Return the contents of the output buffer as a string
chunk($str = null) // Enable response chunking (see the wiki)
dump($obj) // Dump an object
<callback>($arg1, ...) // Call a user-defined helper
<property> // Get a user-defined property
$app->
<callback>($arg1, ...) //Call a user-defined helper
$validator->
notNull() // The string must not be null
isLen($length) // The string must be the exact length
isLen($min, $max) // The string must be between $min and $max length (inclusive)
isInt() // Check for a valid integer
isFloat() // Check for a valid float/decimal
isEmail() // Check for a valid email
isUrl() // Check for a valid URL
isIp() // Check for a valid IP
isAlpha() // Check for a-z (case insensitive)
isAlnum() // Check for alphanumeric characters
contains($needle) // Check if the string contains $needle
isChars($chars) // Validate against a character list
isRegex($pattern, $modifiers = '') // Validate against a regular expression
notRegex($pattern, $modifiers ='')
is<Validator>() // Validate against a custom validator
not<Validator>() // The validator can't match
<Validator>() // Alias for is<Validator>()
许可证
(MIT 许可证)
版权所有 (c) 2010 Chris O'Hara cohara87@gmail.com
特此授予任何获得本软件及其相关文档文件(“软件”)副本的任何人,免费使用该软件的权利,不受限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许获得软件的人这样做,前提是满足以下条件
上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。
本软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于对适销性、特定用途适用性和非侵权的保证。在任何情况下,作者或版权持有人不应对任何索赔、损害或其他责任承担责任,无论该责任是否源于合同行为、侵权行为或其他行为,以及与软件或软件的使用或其他方面有关。