承接 nicollassilva/minasrouter 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nicollassilva/minasrouter

Composer 安装命令:

composer require nicollassilva/minasrouter

包简介

MinasRouter is simple, fast and extremely readable for routes.

README 文档

README

a

Maintainer Scrutinizer Code Quality Software License Latest Version Build Status Code Intelligence Status

MinasRouter is simple, fast and extremely readable for routes. Create and manage your routes in just a few steps.

Simples, rápido e MUITO funcional. MinasRouter é um componente de rotas PHP para projetos MVC! Foi feito para abstrair os verbos RESTfull (GET, POST, PUT, PATCH, DELETE) e renderizar de forma simples e fácil no controller da aplicação.

MinasRouter trabalha e processa todas as informações de forma isolada, facilitando o processo para o desenvolvedor e acelerando o desenvolvimento/andamento do projeto.

Simple, fast and VERY functional. MinasRouter is a PHP routes component for MVC projects! It is designed to abstract the RESTfull (GET, POST, PUT, PATCH, DELETE) verbs and render them simply and easily in the application controller.

MinasRouter works and processes all information in isolation, facilitating the process for the developer and accelerating the development/progress of the project.

Highlights @MinasRouter

  • In a few minutes you can create routes for your application or api (Yes, it really is a few minutes)
  • Fast and Easy middleware system
  • Respect the RESTfull verbs and has great functions to deal with them
  • Route customization, regex in dynamic parameters and optional parameters
  • Spoofing for verbalization and data control (FormSpoofing)
  • Carries dynamic parameters to controller arguments
  • Easy routing groups and fast create
  • It has a Request Class to control and work with route data

With two lines you start using routes!

Application example

Maybe you are a person who learns by watching, you can access the example folder, which contains an folders architecture example of how we use MinasRouter.

Tests

You can check all tests done here. Enjoy!

Installation

MinasRouter is available via Composer require:

"require" {
    "nicollassilva/minasrouter": "^1.0"
}

or run in terminal:

composer require nicollassilva/minasrouter

Documentation

1. Configuration

  • Public Folder Configuration

2. Routes

  • Customization
  • Middlewares
  • Route Groups
  • Others

3. Request Route

  • Methods

Introduction

Para começar a usar o MinasRouter, todo o gerenciamento da navegação deverá ser redirecionado para o arquivo padrão de rotas do seu sistema, que fará todo o processo de tratamento das rotas e retornará o que foi por padrão configurado. Configure conforme os exemplos abaixo e de acordo com seu servidor.

To start using MinasRouter, all navigation management must be redirected to your system's default route file, which will do the entire route handling process and return what was configured by default. Configure according to the examples below and according to your server.

Redirect to Public Folder

RewriteEngine on
Options All -Indexes

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} (www\.)?localhost
RewriteRule (.*) https://%{HTTP_HOST} [L,R=301]

RewriteCond %{REQUEST_URI} !public/
RewriteRule (.*) /public/$1 [L]

apache

RewriteEngine On
#Options All -Indexes

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

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

### Do not use the settings below if you are using developing in a local environment, use only in production.

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

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

nginx

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

The first Route

To start the components:

<?php
    require __DIR__ . "/../vendor/autoload.php";
    
use MinasRouter\Router\Route;

// The second argument is optional. It separates the Controller and Method from the string
// Example: "Controller@method"
Route::start("http://yourdomain.com", "@");

Route::get("/", function() {
    // ...
});

// ... all routes here

// You will put all your routes before this function
Route::execute();

RESTfull Verbs

Methods:

Function Parameter Parameter Parameter
get String $uri $callback
post String $uri $callback
put String $uri $callback
patch String $uri $callback
delete String $uri $callback
match Array $httpVerbs String $uri $callback
any String $uri $callback

Example:

Route::get('/users', [\App\Controllers\User::class, 'index']);
Route::post('/users', [\App\Controllers\User::class, 'store']);
Route::put('/users/{id}', [\App\Controllers\User::class, 'update']);
Route::patch('/users/{id}', [\App\Controllers\User::class, 'update']);
Route::delete('/users/{id}', [\App\Controllers\User::class, 'delete']);

// The router allows you to register routes that respond to any HTTP verb:
Route::any('/', function() {
    // ...
});

// Sometimes you may need to register a route that responds to multiple HTTP verbs:
Route::match(["GET", "POST"], "/", function() {
    // ...
});

Named routes

Methods:

Function Parameter
name String $name
as String $name

Example:

Route::get("/users/create", function() {
    // ...
})->name("user.create");

Route::get("/users/2", function() {
    // ...
})->as("user.show");

Dynamic parameters (required and optional)

Route::get("/", function() {
    // ...
})->name("web.index");

Route::get("/user/{id}", function($id) {
    echo $id;
})->name("user.show");

Route::get("/post/{id?}", function($id) {
    if(!$id) {
        // ...
    }
    
    // ...
})->name("post.show");

Validating a dynamic parameter

Methods:

Function Parameter Parameter
where Array $params
whereParam String $param String $regex
whereNumber String $param
whereAlpha String $param
whereAlphaNumeric String $param
whereUuid String $param

Example:

Route::get("/user/{id}", [\App\Controllers\UserController::class, "show"])
    ->name("user.show")
    ->where(["id" => "[0-9]+"]);

// whereParam is alias of where method
Route::get("/profile/{slug}", [\App\Controllers\UserController::class, "profile"])
    ->name("user.profile")
    ->whereParam("id", "[0-9]+");

Route::get("/book/{id}", [\App\Controllers\BookController::class, "show"])
    ->name("book.show")
    ->whereNumber("id");

Middlewares

Working with middlewares around here is pretty easy, we just need to pass the full names of the classes or set them as global, and from there, we use their alias.

Set Global Middlewares

OBS: It is important that you place all routes below. Routes above this class will not have these middlewares as global.

Route::globalMiddlewares([
    'isLogged' => \App\Middlewares\isLogged::class,
    'isAdmin' => \App\Middlewares\isAdmin::class
]);

// ... all routes

Attach in a route

You may use the middleware method to assign middleware to a route.

Route::get("/musics", function() {
    // ...
})->middleware("isLogged");

Route::get("/musics", function() {
    // ...
})->middleware(["isLogged"]);

You may assign multiple middleware to the route by passing an array of middleware names to the middleware method.

Route::get("/musics", function() {
    // ...
})->middleware("first, second");

Route::get("/movies", function() {
    // ...
})->middleware(["first", "second"]);

When assigning middleware, you may also pass the fully qualified class name:

use App\Middlewares\VerifyCsrfToken;

Route::get("/series", function() {
    // ...
})->middleware(VerifyCsrfToken::class);

Route::get("/series", function() {
    // ...
})->middleware(App\Middlewares\VerifyCsrfToken::class);

Delete a middleware

Sometimes you create a group of routes with middleware, but you want only one or a few routes to be without a specific middleware, you can do that.

Route::middleware(['auth', 'api'])->group(function() {
    Route::get('/', function() {
        // All middlewares will works in this route
    });
    
    Route::get('/no-api', function() {
        // Only the auth middleware works here
    })->withoutMiddleware('api');
});

Route Groups

All methods:

Function Parameter ::function ->function
namespace String $namespace Yes Yes
prefix String $prefix Yes Yes
name String $name Yes Yes
middleware String $middlewares Yes Yes

Group methods can be called static way or normal, don't forget to call a function group to insert as routes inside the closure.

Examples:

Named group

Route::name("admin.")->group(function() {
    Route::get("/", function() {
        // admin.index
    })->name("index");
});

Prefixed group

Route::prefix("admin/")->group(function() {
    Route::get("/index", function() {
        // http://localhost/admin/index
    })->name("index");
});

Default namespace group

Route::namespace("App\Controllers")->group(function() {
    Route::get("/user/{id}", ["User", "show"])->name("show");
    // \App\Controllers\User
});

Default Middleware group

Route::middleware(\App\Middlewares\isLogged::class)->group(function() {
    Route::get("/user/{id}", ["User", "show"])->name("show");
});

Nested group methods

Route::namespace("App\Controllers\Admin")
    ->middleware(["isLogged", "isAdmin"])
    ->name("admin.")
    ->prefix("admin")
    ->group(function() {
    // ...
});

Others

Route with Individual Middleware in group

You can use routes with individual middlewares within a route group.

Route::namespace("isLogged")->group(function() {
    Route::get("/posts", function() {
        // ...
    })->middleware("isAdmin");
    
    // ...
});

Route with Different name in group

Maybe you are wanting a route where you ignore the group name, you can use the second parameter of the name method for that.

Route::name("admin.")->group(function() {
    Route::get("/posts", function() {
        // name: app.posts
    })->name("app.posts", true);
});

Route redirect

Methods:

Function Parameter Parameter Parameter
redirect String $uri String $redirect Int $statusCode = 302
permanentRedirect String $uri String $redirect

Example:

// Returns 302 status code by default.
Route::redirect("/here", "/there");

Route::redirect("/here", "/there", 301);

// permanentRedirect always returns 301
Route::permanentRedirect("/here", "/there");

// You can return an existing route
Route::redirect("/index", "web.index");

Fallback Routes

The fallback route is responsible when there is no route registered with that url address. Whenever there is no route that was requested by the user, the fallback route will be called.

Route::fallback(function() {
    echo 'Route error!';
    // ...
});

OBS: Tenha cuidado caso queira redirecionar para uma rota existente, se nela conter argumentos dinâmicos, ela retornará todo o regex e irá causar erro.

Be careful you redirect to an existing route, because if it has dynamic arguments, it will return the entire regex and error returned.

Request Route

Each time the route is called and the Closure or controller method is called, you will have as a parameter an instance of \MinasRouter\Http\Request. If the route has dynamic parameters (mandatory or optional), they need to be passed before receiving the Request instance.

Function Parameter Parameter
getParams
path
url
fullUrl
header String $header String $default
hasHeader String $header
ip
query ?String $query ?String $default
all ?String $except
getMethod
isMethod String $expectedMethod

The dynamic parameters of the route are directly passed in the method together with a instance of Request.

Example:

use \MinasRouter\Http\Request;

Route::get("/", function(Request $request)) {
   // ... 
});

Route::get("/user/{id}", function($id, Request $request)) {
   // ... 
});

Route::get("/posts/{slug?}", function($slug, Request $request)) {
   // ... 
});

Route::get("/book/{slug}", function($slug, Request $request) {
    // Retrieving all dynamic parameters
    print_r($request->getParams());
});

The Request method is the method that has all your form data, query parameters, dynamic route parameters, and the entire request header.

Request Methods

Retrieving The Request Path

The path method returns the request's path information. So, if the incoming request is targeted at http://localhost/foo/bar, the path method will return foo/bar:

$uri = $request->path();

Retrieving The Request URL

To retrieve the full URL for the incoming request you may use the url or fullUrl methods. The url method will return the URL without the query string, while the fullUrl method includes the query string:

$url = $request->url();

$urlWithQueryString = $request->fullUrl();

Request Headers

You may retrieve a request header from the \MinasRouter\Http\Request instance using the header method. If the header is not present on the request, null will be returned. However, the header method accepts an optional second argument that will be returned if the header is not present on the request:

$value = $request->header("Header-Name");

$value = $request->header("Header-Name", "default");

The hasHeader method may be used to determine if the request contains a given header:

if ($request->hasHeader("Header-Name")) {
    // ...
}

The bearerToken method may be used to retrieve a bearer token from the Authorization header. If no such header is present, null will be returned.

$token = $request->bearerToken();

Request IP Address

The ip method may be used to retrieve the IP address of the client that made the request to your website:

$ipAddress = $request->ip();

Retrieving Data

The query method will only retrieve values from the query string:

$id = $request->query("id");

If the requested query string value data is not present, the second argument to this method will be returned:

$developer = $request->query("developer", "Nicollas");

You may call the query method without any arguments in order to retrieve all of the query string values.

$query = $request->query();

You can access queryString's and input data directly, how properties of the Request class.

// http://localhost/?foo=bar

$foo = $request->foo;

// <input type="text" name="title" value="MinasRouter">

$title = $request->title;

You may retrieve all of the incoming request's input data as an array using the all method. This method may be used regardless of whether the incoming request is from an HTML form or is an XHR request. If you want to nullify some data, you can pass it as a second parameter.

$data = $request->all();

// all, except csrf_token, page
$data = $request->all("csrf_token, page");

Retrieving The Request Method

The getMethod method will return the HTTP verb for the request. You may use the isMethod method to verify that the HTTP verb matches a given string:

$httpMethod = $request->getMethod();

if ($request->isMethod('POST')) {
    // ...
}

nicollassilva/minasrouter 适用场景与选型建议

nicollassilva/minasrouter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 115 次下载、GitHub Stars 达 14, 最近一次更新时间为 2021 年 06 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「route」 「router」 「routes」 「php routing」 「PHP Route」 「Easy Route」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nicollassilva/minasrouter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nicollassilva/minasrouter 我们能提供哪些服务?
定制开发 / 二次开发

基于 nicollassilva/minasrouter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 115
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 14
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 14
  • Watchers: 2
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-06-09