dsisconeto / ciroute
CodeIgniter 路由系统
v0.0.6
2017-09-26 15:24 UTC
README
Ciroute 简单易用,它仅提供面向对象的、更组织和友好的接口来创建开发环境中的路由。在生产环境中,将使用 CodeIgniter 的常规轮盘,因为 CodeIgniter 会转换所有路由并记录在默认路由文件中。
注意!当使用 Ciroute 时,不能再写入默认路由文件,因为每次在开发环境中运行时都会覆盖它。
安装
我们需要通过 composer 安装此包。
composer require dsisconeto/ciroute
配置
在您的项目中的 index.php 文件中,我们将实例化 Ciroute 于开发环境,并仅在该环境中。在文件末尾,在 require Codeigniter 之前,添加以下代码
if (ENVIRONMENT == 'development') { require_once(__DIR__.'/vendor/autoload.php'); new \DSisconeto\Ciroute\Ciroute( __DIR__."/application/config/routes.php", __DIR__."/application/cache/", __DIR__."/application/routes/" ); }
Ciroute 类有三个参数
Ciroute($arquivoDeRotas, $pastaCache, $pastaRotas)
Ciroute 类的参数
- 标准路由文件的完整地址
- 标准缓存文件夹的完整地址
- Ciroute 路由文件的完整地址
路由文件
我们需要创建一个文件夹来存放路由文件,这是 Ciroute 类的第三个参数,在上述代码中传入了 /apliication/routes/ 文件夹,现在只需在此文件夹内创建您想要的任意数量的路由文件。文件名由您自己选择。例如
- /application/routes/site.php
- /application/routes/admin.php
- /application/routes/api.php
使用方法
现在我们将使用 Route 类来创建我们的路由,在定义的任何路由文件夹内的文件中。为了简化访问,在路由文件的开始处使用 "use" 引入 Route 类。
use DSisconeto\Ciroute\Route;
Hello World
Route::get('hello-world', 'Hello_word/index');
代码将在标准路由文件中生成以下输出
$route["hello-world"]["GET"] = ["Hello_word");
创建路由的方法接受两个参数
Route::get($rota, $controler_metodo)]```
- 路由
- 控制器的相同方法
基本上,您可以将两个参数编写为在 CodeIgniter 标准路由系统中编写的方式
使用 HTTP 请求动词
在 Route 类中存在多个方法用于创建路由,每个方法创建具有不同 HTTP 请求动词的路由
Route::get('eventos/cadastrar', 'create'); Route::post('eventos/cadastrar', 'store'); Route::get('eventos/:num/editar', 'edit/$1'); Route::put('eventos/:num/editar', 'update/$1'); Route::delete('eventos/:num', 'delete/$1');
标准路由文件的输出
$route["eventos/cadastrar"]["GET"]="eventos/create"; $route["eventos/cadastrar"]["POST"]="eventos/store"; $route["eventos/:num/editar"]["GET"]="eventos/edit/$1"; $route["eventos/:num/editar"]["PUT"]="eventos/update/$1"; $route["eventos/:num"]["DELETE"]="eventos/delete/$1";
命名路由的辅助函数
function ciroute($name, $arguments = []) { static $routes; static $regex = "/\(:([A-Za-z0-9_.-]*)\)/"; if (!$routes) $routes = include(__DIR__ . "/../cache/ciroute_names.php"); if (!isset($routes[$name])) { throw new \Exception("Não existe o nome($name) dessa rota"); } if (!is_array($arguments)) { throw new \Exception("O segundo argumento tem que ser um array"); } $count = 0; $route = preg_replace_callback($regex, function () use (&$count, $arguments) { return ($arguments[$count++]); }, $routes[$name]); return base_url($route); }