pyrsmk/lumy

该软件包已被废弃且不再维护。作者建议使用 pyrsmk/lumy3 软件包。

最小化的CLI/HTTP框架

2.9.3 2016-05-26 17:46 UTC

This package is auto-updated.

Last update: 2022-02-01 12:44:06 UTC


README

Lumy 2 仓库现在不再维护,推荐使用 Lumy 3。这个新版本是一个大转变,因为整个框架已经被 Slim 所取代。我们只是保留了一个Slim的包装器,以便也能使用 Chernozem

Lumy 是一个 最小化 的微 CLI/HTTP 框架,旨在快速、高效且易于扩展,以满足您使用任何外部组件的需求。它基于 Chernozem,以提供依赖注入的高效方式。

Lumy 应运而生,因为像 SilexSlim 这样的微框架仍然太大,并且处理了许多可以由许多现有库管理的功能。它们通常也过于面向 Web:PHP 在 CLI 环境中也同样出色。

它包括 CLI/HTTP 路由器、环境对象和中间件堆栈。

安装

获取源代码或使用 Composer 安装

composer require pyrsmk/lumy

如果您不是使用 Composer 安装,别忘了也要加载其依赖项: ChernozemLongueVue

快速示例

$lumy=new Lumy\Http;

// Add a middleware to configure our template engine (with [Twig](http://twig.sensiolabs.org/))
$lumy->middleware(function($middlewares) use($lumy){
    $lumy['twig']=new Twig_Environment(
        new Twig_Loader_Filesystem($lumy['dirs']['templates']),
        $options
    );
    $middlewares->next();
});

// Add a basic route that do nothing but display our index page
$lumy->get('/',function() use($lumy){
    // Provide a rooturi variable to the template is really useful for CSS, images, scripts inclusion
    echo $lumy['twig']->render('index.tpl',array(
        'rooturi' => $lumy['environment']->getRootUri()
    ));
});

// Specify an error handler, throwed when an exception has been catched
$lumy->error(function($e) use($lumy){
    echo $lumy['twig']->render('error.tpl',array(
        'rooturi' => $lumy['environment']->getRootUri(),
        'message' => $e->getMessage()
    ));
});

// Run the application and print the response body
echo $lumy->run();

基础

Lumy 对象是一个单例,可以通过

$lumy=Lumy\Http::getInstance();

添加 CLI 路由

在 CLI 环境中添加路由的基本方式是

$lumy->route('--help',function(){
    // Will print 'Some help' when the 'your_app --help' command is called
    echo 'Some help';
});

我们可以指定一个路由链数组

$chains=array('--help','-h');
$lumy->route($chains,function(){
    echo 'Some help';
});

由于路由系统基于 LongueVue,我们可以使用缩略语来提取选项

$lumy->route('install {directory}',function($directory){
    // Some actions
});

有些情况下,我们需要验证命令语法是否有效。我们可以通过使用正则表达式来验证命令。如果指定的正则表达式既不匹配路由也不

$lumy->route('remove user {id}',function($id){
    // Some actions
},array(
    'directory' => '\d+'
));

还有其他一些情况,我们希望从我们的缩略语中获得默认值

// The 'show' command will show tables by default
$lumy->route('show {arg}',function($arg){
    // Some actions
},array(
    'arg' => 'databases|tables'
),array(
    'arg' => 'tables'
));

使用 HTTP 环境添加路由

HTTP 路由在 CLI 环境中的工作方式与之前相同,但 route() 方法已被 get()post()put()delete() 替换。以下是几个示例来说明这种情况

$lumy->get('/gallery',function(){
    // Display the gallery
});

$lumy->put('/gallery',function(){
    // Add a new picture
});

$lumy->delete('/gallery/{id}',function($id){
    // Delete the specified picture
});

请注意,PUTDELETE 请求的工作方式与 POST 请求相同。它们的数据将从 $_POST[] 数组中可用。如果您需要添加自定义路由,请使用 map() 方法

$lumy->map('SEARCH','/gallery/{terms}',function($terms){
    // Display the gallery
});

HTTP上下文添加了一些新常量,以简化路由的编写

  • %scheme%:匹配http和'https'
  • %host%:匹配当前主机
  • %requesturi%:匹配请求URI(它是根URI加上资源URI)
  • %rooturi%:匹配根URI(主机和你的网站相对路径之间的所有内容)
  • %resourceuri%:匹配资源URI(属于你的网站的具体URI)
$lumy->get('%scheme%://{user}.mywebsite.com/profile',function($user){
    // Show the requested user profile
},array(
    'user' => '\w+'
));

如果需要,你可以使用预定义的路由来组装一个URL

// Name the route to register
$lumy->get('/gallery/{id}',function(){
    // Some actions
},null,null,'gallery');

// ...

// Assemble an URL to include to your page/template
// This will print '/gallery/72'
echo $lumy->assembleUrl('gallery',array('id'=>72));

正如你可能已经猜到的,HTTP上下文会发送REST请求。但是PUTDELETE请求在HTML中不支持。因此,为了知道发送了哪种请求,Lumy会监视$_POST['_METHOD']变量以确定要使用的方法。在你的表单中添加一个<input name="_METHOD" value="DELETE">。还有一个,它可以通过即时执行同步REST请求来简化整个过程。

注册自定义值和服务

由于Lumy建立在Chernozem之上(我们建议您阅读其文档),它支持包含变量和,更有趣的是,服务

// Define the 'session' closure
$lumy['session']=function(){
    return new Session();
};
// Set the closure as a service
$lumy->service('session');

现在,当服务被检索时,Session对象会自动实例化。这允许我们只为请求的页面渲染而加载我们真正需要的对象。

// The Session object is ready
$lumy['session']['auth']=true;

中间件

在Lumy中,我们使用中间件来模块化应用程序。每个中间件都是一个简单的闭包/回调,在运行时按定义的顺序逐个调用。每个中间件都需要调用下一个中间件本身,这允许将所有中间件包装在一个函数中。当Lumy运行时,会自动创建一个中间件来运行路由函数。然后,请记住,您可以将任何中间件包装在整个应用程序中。

$lumy->middleware(function($middlewares){
    // Define our session service
    $lumy['session']=function(){
        return new Session();
    };
    $lumy->service('session');
    // Call the next middleware
    $middlewares->next();
    // Clean up session when the application has been runned
    unset($lumy['session']['cache']);
});

处理错误

错误处理程序由error()方法定义,它接受一个回调

$lumy->error(function($exception){
    // Print the encountered error
    echo $exception->getMessage();
});

运行应用程序

当你准备好了,你可以

$lumy->run();

请求对象

所有请求对象都有一个getChain()方法,它返回请求的整个请求/命令链。您可以使用$lumy['request']检索此对象。

命令行界面(CLI)

CLI请求对象相当简洁。它实现了两个方法来处理命令链(以下示例基于myapp install install/path/命令)

  • getArguments():获取传递的命令的参数数组(例如:['install', 'install/path/']
  • getApplicationName():获取应用程序名称(例如:myapp

HTTP

HTTP请求对象实现了几个有用的函数来处理HTTP请求(以下示例基于http://mywebsite.com/app/gallery/7请求)

  • getScheme():获取请求的方案,可以是httphttps
  • getHost():获取主机(例如:mywebsite.com
  • getPort():获取请求的端口(例如:80
  • getRequestUri():获取请求URI(相对于当前主机的请求链)(例如:/app/gallery/7
  • getRootUri() : 获取根URI(它是请求相对于您的应用程序/网站的路径)(示例: /app
  • getResourceUri() : 获取资源URI(它是相对于您应用程序/网站特定请求的路径)(示例: /gallery/7
  • getMethod() : 获取请求方法(通常是 GETPOSTPUTDELETE
  • isAjax() : 如果是AJAX请求则为true
  • isFlash() : 如果是AMF请求则为true
  • isSecure() : 如果是HTTPS请求则为true
  • getClientIp() : 获取客户端IP

响应对象

响应对象实现了4种用于管理响应体的方法。您可以使用 $lumy['response'] 获取此对象。

它还实现了一个 __toString() 函数,可以直接打印Lumy在应用程序运行后返回的响应对象

echo $lumy->run();

以下是我们的响应体管理方式

  • setBody($body) : 设置响应对象的主体
  • prependBody($body) : 将内容添加到主体开头
  • appendBody($body) : 将内容添加到主体末尾
  • getBody() : 返回主体

CLI

CLI响应对象有用于设置/获取环境变量和设置ANSI颜色的方法

  • setVariable($name,$value) : 设置环境变量
  • getVariable($name) : 获取环境变量
  • unsetVariable($name) : 删除变量
  • colorize($color,$background,$style) : 返回ANSI颜色
  • reset() : 返回用于重置颜色和样式的ANSI代码

为了方便起见,此响应对象包含与 colorize() 一起使用的ANSI代码常量

  • 颜色: BLACKREDGREENYELLOWBLUEPURPLECYANGREY
  • 样式: BOLDDIMUNSERLINEBLINKHILIGHTHIDESTROKE

HTTP

HTTP响应对象可以管理头部、状态码,并提供一些用于处理浏览器的有用函数

  • setHeader($name,$value) : 设置头部
  • getHeader($name) : 获取头部
  • unsetHeader($name) : 删除头部
  • setStatus($code) : 设置发送到浏览器的状态码
  • getStatus() : 获取状态码
  • redirect($url,$status) : 跳转到指定的绝对/相对URL;默认发送的状态码是 302
  • send($path) : 强制浏览器发送下载
  • display($path) : 强制浏览器显示文件(通常是图像)

公开目录

由于我们经常在一个项目中遇到多个不同的服务器(至少,您的本地和远程服务器),Lumy就像一个防火墙选项,根据需要允许或禁止访问您的文件。将所有请求都指向您的应用程序文件(index.php)(或类似文件):现在所有请求都通过Lumy传递。我们只需允许/拒绝我们需要的。

// The user will freely access to the files in images/, uploads/ and config/
$lumy->publish('/images');
$lumy->publish('/uploads');
$lumy->publish('/config');

// But he won't access to sensible data
$lumy->unpublish('/config/database.json');

路由的高级使用

路由机制用于内部,我们通常不必关心它,否则在某些情况下我们希望直接处理路由。为此,我们应该通过将名称作为 route()get()post() 等函数的最后一个参数传递来命名我们的路由。

// Add a 'gallery' route
$lumy->get('/gallery',function(){
    // Some actions
},null,null,'gallery');

然后你可以使用 $lumy['router']['gallery'] 来获取路由并访问以下方法:

  • match($chain):将指定的链与路由链进行匹配
  • getChain():返回路由链
  • getMatcher():返回用于验证路由链是否针对当前请求有效的匹配器对象(更多信息,请参见LongueVue 项目)
  • getController():返回与此路由注册的控制器

许可证

Lumy 在 MIT 许可证 下发布。