eric-chau/jarvis

Jarvis 是一个 PHP 7.1 微型框架

v2.0.0 2017-01-21 15:12 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:25:54 UTC


README

Code Climate Test Coverage Build Status SensioLabsInsight Scrutinizer Code Quality

Jarvis 是一个 PHP 7.1 微型框架。它被设计成简单且轻量。

注意:如果您想使用 Jarvis 与 PHP 5.6 一起使用,请切换到 0.1 分支或使用 v0.1.* 标签。

Jarvis 需要 php >= 7.1。它基于自己的依赖注入容器、来自 Symfony 的 http 基础组件和 nikic 的快速路由。

用法

<?php

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

$jarvis = new Jarvis\Jarvis();

$jarvis->router
    ->beginRoute('default')
        ->setMethod('get')
        ->setPattern('/')
        ->setHandler(function () {
            return 'Hello world!';
        })
    ->end()
;

$response = $jarvis->run();

$response->send();

Jarvis 处理传入请求的方式

以下架构将总结 Jarvis\Jarvis::run() 如何处理任何传入请求

INPUT: an instance of Request

|
|__ Step 1: broadcast RunEvent.
|
|__ Step 2: check if RunEvent has a response?
|_______
| NO    | YES
|       |
|       |_ RETURN Response
|
|__ Step 3: resolve URI
|
|__ Step 4: does request match any route?
|_______
| NO*   | YES
|       |
|       |_ Step 4a: broadcast ControllerEvent
|       |
|       |_ Step 4b: invoke callback to process the request
|       |
|<------
|
|_ Step 5: broadcast ResponseEvent
|
|_ RETURN Response

OUT: an instance of Response

*: 注意,如果提供的 URI 不匹配任何路由,则 run() 将返回一个包含 404 或 406 状态码的 Response 实例。

路由技能

Jarvis 的路由器可以处理匿名和命名路由。默认情况下,路由是 HTTP GET 方法类型,模式设置为 /。以下是一些示例

匿名路由,HTTP 方法 GET,模式 /

<?php

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

$jarvis = new Jarvis\Jarvis();

$jarvis->router
    ->beginRoute()
        ->setHandler(function () {
            return 'foobar!';
        })
    ->end()
;

命名路由,名称:user_edit,HTTP 方法:PUT,模式:/user/{id}

注意,id 必须是一个数字。让我们看看如何做到这一点。

<?php

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

$jarvis = new Jarvis\Jarvis();

$jarvis->router
    ->beginRoute('user_edit')
        ->setMethod('PUT')
        ->setPattern('/user/{id:\d+}')
        ->setHandler(function ($id) {
            // Do some stuff

            return "User $id informations are now up-to-date!";
        })
    ->end()
;

echo $jarvis->router->uri('user_edit', ['id' => 123]); // print '/user/123'

依赖注入容器技能

Container::alias()

Jarvis 的 DIC(依赖注入容器)可以处理别名

<?php

$jarvis = new Jarvis\Jarvis();

$jarvis['foo'] = 'hello world';
$jarvis->alias('bar', 'foo');

$jarvis['foo'] === $jarvis['bar']; // = true

Container::find()

::find() 是 Jarvis 的 DIC 提供的另一个有用方法

<?php

$jarvis = new Jarvis\Jarvis();

$jarvis['dicaprio_movie_1997'] = 'Titanic';
$jarvis['dicaprio_movie_2010'] = 'Inception';
$jarvis['dicaprio_movie_2014'] = 'The Wolf of Wall Street';

$jarvis->find('dicaprio_movie_*'); // = ['Titanic', 'Inception', 'The Wolf of Wall Street']
$jarvis->find('dicaprio_movie_19*'); // = ['Titanic']
$jarvis->find('dicaprio_movie_2015'); // = []