PHP 路由系统

dev-main 2023-11-17 16:45 UTC

This package is auto-updated.

Last update: 2024-09-17 18:40:15 UTC


README

小巧、简单、简单。路由器是一个具有 MVC 抽象的 PHP 路由组件。准备 RESTful 动词(GET、POST、PUT、PATCH 和 DELETE),在独立层上运行,可以无秘密集成到您的应用程序中。

小、简单、不复杂。路由器是一个具有 MVC 抽象的 PHP 路由组件。准备 RESTful 动词(GET、POST、PUT、PATCH 和 DELETE),在其独立层上工作,可以无秘密集成到您的应用程序中。

亮点

  • 带有所有 RESTful 动词的路由器类(Classe router com todos os verbos RESTful)
  • 具有完全决策控制的优化调度(Despacho otimizado com controle total de decisões)
  • 请求欺骗以进行本地表述(Falsificador (Spoofing) de requisição para verbalização local)
  • 为您的应用程序或 API 创建路由非常简单(É muito simples criar rotas para sua aplicação ou API)
  • 控制器触发器和数据载体(Gatilho e transportador de dados para o controloador)
  • Composer 就绪且符合 PSR-2(Pronto para o composer e compatível com PSR-2)

安装

路由器可通过 Composer 获取

"jpsistemasbr/router": "1.0.*"

或运行

composer require jpsistemasbr/router

文档

有关如何使用路由器的详细信息,请参阅组件目录中的示例文件夹。要使用路由器,需要将您的路由导航(index.php)重定向到所有流量都必须处理的地方。下面的示例显示了如何

有关如何使用路由器的更多详细信息,请参阅组件目录中的示例文件夹。要使用路由器,需要将您的路由导航重定向到根路由文件(index.php),所有流量都必须在此处理。下面的示例显示了如何

Apache

RewriteEngine On
#Options All -Indexes

## ROUTER WWW Redirect.
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

## ROUTER HTTPS Redirect
#RewriteCond %{HTTP:X-Forwarded-Proto} !https
#RewriteCond %{HTTPS} off
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ROUTER URL Rewrite
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?route=/$1 [L,QSA]

Nginx

location / {
  if ($script_filename !~ "-f"){
    rewrite ^(.*)$ /index.php?route=/$1 break;
  }
}
路由
<?php

use Jpsistemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

/**
 * routes
 * The controller must be in the namespace Test\Controller
 * this produces routes for route, route/$id, route/{$id}/profile, etc.
 */
$router->namespace("Test");

$router->get("/route", "Controller:method");
$router->post("/route/{id}", "Controller:method");
$router->put("/route/{id}/profile", "Controller:method");
$router->patch("/route/{id}/profile/{photo}", "Controller:method");
$router->delete("/route/{id}", "Controller:method");

/**
 * group by routes and namespace
 * this produces routes for /admin/route and /admin/route/$id
 * The controller must be in the namespace Dash\Controller
 */
$router->group("admin")->namespace("Dash");

$router->get("/route", "Controller:method");
$router->post("/route/{id}", "Controller:method");

/**
 * sub group
 */
$router->group("admin/support");

$router->get("/tickets", "Controller:method");
$router->post("/ticket/{id}", "Controller:method");

/**
 * Group Error
 * This monitors all Router errors. Are they: 400 Bad Request, 404 Not Found, 405 Method Not Allowed and 501 Not Implemented
 */
$router->group("error")->namespace("Test");
$router->get("/{errcode}", "Coffee:notFound");

/**
 * This method executes the routes
 */
$router->dispatch();

/*
 * Redirect all errors
 */
if ($router->error()) {
    $router->redirect("/error/{$router->error()}");
}
命名
<?php

use Jpsistemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

/**
 * routes
 * The controller must be in the namespace Test\Controller
 */
$router->namespace("Test")->group("name");

$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");

/**
 * This method executes the routes
 */
$router->dispatch();

/*
 * Redirect all errors
 */
if ($router->error()) {
    $router->redirect("name.hello");
}
命名控制器示例
<?php

class Name
{
    public function __construct($router)
    {
        $this->router = $router;
    }

    public function home(): void
    {
        echo "<h1>Home</h1>";
        echo "<p>", $this->router->route("name.home"), "</p>";
        echo "<p>", $this->router->route("name.hello"), "</p>";
        echo "<p>", $this->router->route("name.redirect"), "</p>";
    }

    public function redirect(): void
    {
        $this->router->redirect("name.hello");
    }
}
命名参数
<?php

use Jpsistemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

$this->router->route("name.params", [
    "category" => 22,
    "page" => 2
]);

//result
//https://www.youdomain.com/name/params/22/page/2

$this->router->route("name.params", [
    "category" => 22,
    "page" => 2,
    "argument1" => "most filter",
    "argument2" => "most search"
]);

//result
//https://www.youdomain.com/name/params/22/page/2?argument1=most+filter&argument2=most+search
可调用
<?php

use Jpsisemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

/**
 * GET httpMethod
 */
$router->get("/", function ($data) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>GET :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});

/**
 * GET httpMethod and Route
 */
 $router->get("/", function ($data, Router $route) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>GET :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
    var_dump($route->current());
});

/**
 * POST httpMethod
 */
$router->post("/", function ($data) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>POST :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});

/**
 * PUT spoofing and httpMethod
 */
$router->put("/", function ($data) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>PUT :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});

/**
 * PATCH spoofing and httpMethod
 */
$router->patch("/", function ($data) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>PATCH :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});

/**
 * DELETE spoofing and httpMethod
 */
$router->delete("/", function ($data) {
    $data = ["realHttp" => $_SERVER["REQUEST_METHOD"]] + $data;
    echo "<h1>DELETE :: Spoofing</h1>", "<pre>", print_r($data, true), "</pre>";
});

$router->dispatch();
简单中间件
<?php

use Jpsistemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

//simple
$router->get("/edit/{id}", "Coffee:edit", middleware: \Http\Guest::class);
$router->get("/denied", "Coffee:denied", "coffe.denied", \Http\Group::class);

//multiple
$router->get("/logado", "Coffee:logged", middleware: [\Http\Guest::class, \Http\Group::class]);

//callable
$router->get("/call", function ($data, Router $router){
    //code here
}, middleware: \Http\Guest::class);
简单中间件组
<?php

use Jpsistemasbr\Router\Router;

$router = new Router("https://www.youdomain.com");

//group single or multiple
$router->group("name", \Http\Guest::class);
$router->get("/", "Name:home", "name.home");
$router->get("/hello", "Name:hello", "name.hello");
$router->get("/redirect", "Name:redirect", "name.redirect");
简单中间件类示例
<?php

namespace Http;

use Jpsistemasbr\Router\Router;

class User
{
    public function handle(Router $router): bool
    {
        $user = true;
        if ($user) {
            var_dump($router->current());
            return true;
        }
        return false;
    }
}
表单欺骗
此示例展示了如何从应用程序访问路由(PUT、PATCH、DELETE)。您可以在示例文件夹中查看更多详细信息。注意 _method 字段,它可以是隐藏类型的。

此示例展示了如何从应用程序访问路由(PUT、PATCH、DELETE)。您可以在示例文件夹中查看更多详细信息。注意 _method 字段,它可以是隐藏类型的。

<form action="" method="POST">
    <select name="_method">
        <option value="POST">POST</option>
        <option value="PUT">PUT</option>
        <option value="PATCH">PATCH</option>
        <option value="DELETE">DELETE</option>
    </select>

    <input type="text" name="first_name" value="JPsistemas"/>
    <input type="text" name="last_name" value="Leite"/>
    <input type="text" name="email" value="jpsistemasbr@gmail.com"/>

    <button>Jpsistemasbr</button>
</form>
PHP cURL 示例
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https:///jpsistemasbr/router/example/spoofing/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",
  CURLOPT_POSTFIELDS => "first_name=JP&last_name=Sistemas&email=jpsistemasbr%40gmail.com",
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Content-Type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

支持

安全:如果您发现任何与安全相关的问题,请通过电子邮件 jpsistemasbr@gmail.com 而不是使用问题跟踪器。

如果您发现任何与安全相关的问题,请通过电子邮件 jpsistemasbr@gmail.com 而不是使用问题跟踪器。

谢谢

许可

MIT 许可证(MIT)。请参阅 许可文件 了解更多信息。