needinfo/router
Composer 安装命令:
composer require needinfo/router
包简介
Um roteador PHP simples, seguro e robusto criado para agilidade na abstração MVC através de verbos RESTful.
README 文档
README
Small, simple and uncomplicated. The router is a PHP route components with abstraction for MVC. Prepared with RESTfull verbs (GET, POST, PUT, PATCH and DELETE), works on its own layer in isolation and can be integrated without secrets to your application.
Pequeno, simples e descomplicado. O router é um componentes de rotas PHP com abstração para MVC. Preparado com verbos RESTfull (GET, POST, PUT, PATCH e DELETE), trabalha em sua própria camada de forma isolada e pode ser integrado sem segredos a sua aplicação.
Needinfo is a set of small and optimized PHP components for common tasks. With them you perform routine tasks with fewer lines, writing less and doing much more.
Needinfo é um conjunto de pequenos e otimizados componentes PHP para tarefas comuns. Com eles você executa tarefas rotineiras com poucas linhas, escrevendo menos e fazendo muito mais.
- Router class with all RESTful verbs (Classe router com todos os verbos RESTful)
- [NEW no v2.0] Regex Constraints nos parâmetros de URL
- [NEW no v2.0] Retorno
405 Method Not Allowedestruturado (+ Allow Headers) - [NEW no v2.0] Encadeamento de Rotas (
->name(),->middleware(),->with()) - [NEW no v2.0] Matcher Desacoplado para uso focado em Frameworks que precisam ingerir uma Request customizada (Injeção de PSR-11 support).
- Optimized dispatch with total decision control (Despacho otimizado com controle total de decisões)
- Composer ready and PSR-4 compliant (Pronto para o composer e compatível com PSR-4)
Installation
Router is available via Composer:
composer require needinfobr/router "^2.0"
Documentation
For details on how to use the router, see the sample folder with details in the component directory. To use the router you need to redirect your route routing navigation (index.php) where all traffic must be handled. The example below shows how:
Para mais detalhes sobre como usar o router, veja a pasta de exemplo com detalhes no diretório do componente. Para usar o router é preciso redirecionar sua navegação para o arquivo raiz de rotas (index.php) onde todo o tráfego deve ser tratado.
Apache (.htaccess)
RewriteEngine On #Options All -Indexes ## 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; } }
1. Basic usage and MVC Pattern
<?php use Needinfo\Router\Router; $router = new Router("https://www.youdomain.com"); /** * The controller must be in the namespace App\Controllers */ $router->namespace("App\\Controllers"); $router->get("/", "Web:home"); // Default parameters catch anything [^/]+ $router->post("/route/{id}", "Web:method"); // You can use Regex Constraints (v2.0+) $router->get("/users/{id:\d+}", "Web:user"); // id only matches Numbers! $router->get("/posts/{slug:[a-z\-]+}", "Web:post"); // slug only matches lowercase and hyphens! /** * Group by routes and namespace * The controller must be in the namespace App\Controllers\Admin */ $router->group("admin")->namespace("App\\Controllers\\Admin"); $router->get("/route", "Dashboard:home"); /** * This method executes the routes directly based on $_SERVER */ $router->dispatch(); /* * Redirect all errors */ if ($router->error()) { $router->redirect("/error/{$router->error()}"); // e.g., 404 or 405 }
2. Route Decorators (v2.0+)
Agora toda chamada de rota retorna o objeto Needinfo\Router\Route, que permite você injetar dados avançados usados pelo seu sistema MVC:
$route = $router->get("/dashboard", "Web:dashboard") ->name("admin.dashboard") ->middleware("RequireAuth") ->with(["role" => "admin"]);
3. Framework Integrations e Dependency Injection (v2.0+)
Injeção Container Simples
Se seu index for impulsionado por um container, basta setá-lo no Roteador antes do dispatcher. Se houver métodos como has e get (PSR-11), o Router fará ->get('App\Controllers\Web') garantindo autowiring!
$router->setContainer($myContainer); $router->dispatch();
Passagem de Contexto (Context Injection)
Muitos frameworks enviam o Request para o Controller ou Callable. Agora você pode passar na chamada de $router->dispatch($context) e recuperar lá dentro:
$router->get("/api/user", function($request, $params) { echo $request->getBody(); // $request é o contexto customizado repassado }); $router->dispatch($request);
Matcher Desacoplado
Não quer rodar a lógica new Controller direto do core do Router? Quer varrer e ver se algo casou apenas? O comando match() responde uma Query estruturada!
$match = $router->match('POST', '/api/users'); if ($match->isSuccess()) { $matchedRoute = $match->getRoute(); $params = $match->getParams(); // Voce assume o controle da execução: // (new $matchedRoute->getHandler())($params); } elseif ($match->getError() === 405) { echo "Metodos aceitos: " . implode(', ', $match->getAllowedMethods()); } else { echo "404 Not Found"; }
Contributing
Please see CONTRIBUTING for details.
Support
Security: If you discover any security related issues, please email contato@needinfo.com.br instead of using the issue tracker.
License
The MIT License (MIT).
needinfo/router 适用场景与选型建议
needinfo/router 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「route」 「routing」 「php」 「router」 「needinfo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 needinfo/router 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 needinfo/router 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 needinfo/router 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Provide a way to secure accesses to all routes of an symfony application.
Write down your routing mapping at one place
A Laravel-like router for the WordPress Rewrite API
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.
A Laravel helper to detect if the current route/path is active.
Client for Google Directions API to add interpolated points to a route consisting of given coordinates.
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 35
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-04-04