nearbycreative/light-framework

Light Framework让创建强大的JSON API变得极其简单

0.3.3 2021-08-01 21:08 UTC

This package is auto-updated.

Last update: 2024-09-29 05:42:34 UTC


README

Light是一个用于快速启动强大API的微框架。它可以作为独立框架使用,也可以嵌入到现有应用中。

Laravel和Symfony等框架功能强大,但当你需要构建API时,一个包含所有功能的Web框架可能会因为选项过多而过于复杂。

Light旨在使用Eloquent和Phinx等熟悉的开源技术,以及MVC等简单范式,使构建API变得非常快速。

要求

  • php7.2+
  • 启用了mod_rewrite功能的Web服务器

快速启动新项目

如果您从零开始创建项目,以下命令将帮助您快速启动!

mkdir myproject && cd myproject

composer require nearbycreative/light-framework

./vendor/bin/light init   
php light serve

就这么多!您可以通过https://:8080来查看Light的实际应用!

目录结构

light init创建以下目录结构

app/
    controller/
        Welcome.php
    model/
database/
    migrations/
    seeds/
public/
    .htaccess
    index.php
resources/
    js/
    sass/
    views/
.env
light

注意,这是获取新应用快速启动的默认脚手架。如果您要将Light集成到现有项目中,您可能不需要运行light init,而是将其嵌入。学习如何在现有应用中嵌入Light

使用路由闭包

如果您查看生成的public/index.php,您会看到它提供了一些简单的路由以供您开始。如果您愿意,您可以使用路由闭包在单个文件中创建整个应用,例如

示例index.php

require_once __DIR__ . '/../vendor/autoload.php';

$app = new \Light\App();
$route = $app->routes;

$route->get('/test', function() {
    return ['hello' => 'world'];
});

$route->get('/test/{slug}', function($slug) {
    return ['slug' => $slug];
});

使用php light serve命令启动测试服务器。

访问:https://:8080/test

您将看到以下输出

{
    "code": 200,
    "status": "success",
    "time": "2020-02-02T05:09:15.457290Z",
    "data": {
        "hello": "world"
    }
}

访问:https://:8080/test/this-is-cool

您将看到以下输出

{
    "code": 200,
    "status": "success",
    "time": "2020-02-02T05:09:15.457290Z",
    "data": {
        "slug": "this-is-cool"
    }
}

使用控制器

将所有API端点放在路由闭包中对于小型API来说工作得很好。然而,这可能会很快变得相当复杂。另一种组织API代码的方式是使用Light控制器。

您可以在应用程序中创建一个继承自Light\Controller的控制器,或者使用php light make:controller命令。

例如:php light make:controller Test将在_app/Controller/Test.php中生成以下控制器

<?php

namespace App\Controller;

/**
 * Test Controller
 *
 * @packaage App\Controller
 */
class Test extends \Light\Controller
{

    /**
     * Index
     */
    public function index()
    {
        return ['hello' => 'world'];
    }

}

index.php中添加以下路由,指向您刚刚创建的控制器的操作

$route->get('/foo', Test::class . '@index');

使用php light serve测试您的新的API端点

访问:https://:8080/foo

命令行工具

尝试运行php light help来了解您可以使用命令行脚本做什么。

了解更多

以下文档即将推出!