heartbeat/loris

一个ReactPHP API应用程序模板,用于创建非常快的API!

1.0.0 2020-12-14 11:08 UTC

This package is auto-updated.

Last update: 2024-08-28 17:00:59 UTC


README

一个ReactPHP API应用程序模板,用于创建非常快的API!

Latest Stable Version Total Downloads Latest Unstable Version License

Heartbeat Loris

洛里斯是现存最慢的动物之一,这个库与它相反!

包含

  • 基于动作的路由(路由XYZ应打开动作XYZ)
  • CORS中间件。
  • 依赖注入和容器定义。
  • HTTP浏览器从另一个API获取数据。
  • 处理JSON数据的辅助工具。

安装

该软件包仅通过composer提供

composer require heartbeat/loris

应用

创建一个包含LORIS应用程序的index.php文件

<?php

use Heartbeat\Loris\Application;

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

$app = new Application('0.0.0.0:8001');
$app->addAction(MyAction::class);
// builds the server, register informations
$app->server();
// start the loop run
$app->run();

创建MyAction动作

<?php

namespace App\Actions;

use Heartbeat\Loris\Action;
use Heartbeat\Loris\Response\JsonResponse;

class MyAction extends Action
{
    public function route(): string
    {
        return '/my-super-action';
    }

    public function run(array $params)
    {
        return new JsonResponse(200, [
            'message' => [
                'hello world!'
            ]    
        ]);
    }
}

或者一个示例,该示例生成一个动作,该动作会调用另一个API

<?php

namespace App\Actions;

use Heartbeat\Loris\Action;
use Heartbeat\Loris\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface;
use Clue\React\Buzz\Browser;

class MyAction extends Action
{
    public function route(): string
    {
        return '/my-super-action';
    }

    public function run(array $params)
    {
        $client = new Browser($this->loop);
        return $client->get('https://api.example.com')->then(function(ResponseInterface $reponse) {
            // create the response from 
            $content = (string) $reponse->getBody();

            // ... do something with content :-)
        
            return new JsonResponse(200, ['message' => $content]);
        });
    }
}

在动作中,您可以做任何您想做的事情,在我们的示例中,我们从API获取信息并返回这些信息。

现在您可以访问localhost:8001/my-upser-action,该动作返回上述动作的内容。

使用DI

为了在您的应用程序内部注册和重用任何对象,您可以使用以下简单的DI机制

$app = new Application('0.0.0.0:8001');
$app->addDefintion(MyDiExample::class, function() {
    return New MyDiExample();
});

现在您可以通过构造函数参数在动作中访问DI定义

class TestAction extends Action
{
    public function __construct(MyDiExample $myDiExample)
    {
        var_dump($myDiExample);
    }
}