alsemany/route

简单的PHP路由类。

0.1 2017-12-06 01:56 UTC

This package is not auto-updated.

Last update: 2024-09-23 08:04:21 UTC


README

从 noahbuscher/Macaw 分支出来

路由

路由是一个简单、开源的PHP路由器。它非常小巧(约150行代码),运行速度快,并且拥有优秀的注释源代码。这个类允许您将其直接放入项目中并立即开始使用。

安装

Composer

如果您有Composer

# composer require alsemany/route

从发布中下载

https://github.com/alsemany/route/releases 下载Zip文件或tar.gz

示例

首先,使用 Route 命名空间

use \Alsemany\Route\Route;

Route 不是一个对象,因此您可以直接对该类进行操作。以下是一个Hello World示例

Route::get('/', function() {
  echo 'Hello world!';
});

Route::dispatch();

Route 还支持lambda URI,例如

Route::get('/(:any)', function($slug) {
  echo 'The slug is: ' . $slug;
});

Route::dispatch();

您还可以在Route中对HTTP方法进行请求,因此您也可以这样做

Route::get('/', function() {
  echo 'I'm a GET request!';
});

Route::post('/', function() {
  echo 'I'm a POST request!';
});

Route::any('/', function() {
  echo 'I can be both a GET and a POST request!';
});

Route::dispatch();

最后,如果没有为某个位置定义路由,您可以让Route运行自定义回调,例如

Route::catchall(function() {
  echo 'Catching All 404 Errors :: Not Found';
});

如果您没有指定错误回调,Route将直接输出404

为了让服务器知道URI不指向真实文件,您可能需要使用以下示例之一配置文件

将示例传递到控制器而不是闭包

有可能将命名空间路径传递到控制器而不是闭包

在这个演示中,假设我有一个名为controllers的文件夹,其中有一个demo.php文件

index.php

require('vendor/autoload.php');

use Alsemany\Route\Route;

Route::get('/', 'Controllers\demo@index');
Route::get('page', 'Controllers\demo@page');
Route::get('view/(:num)', 'Controllers\demo@view');

Route::dispatch();

demo.php

<?php
namespace controllers;

class Demo {

    public function index()
    {
        echo 'home';
    }

    public function page()
    {
        echo 'page';
    }

    public function view($id)
    {
        echo $id;
    }

}

这是通过Composer安装Route的示例。

composer.json

{
   "require": {
        "alsemany/Route": "^0.1.0"
    },
    "autoload": {
        "psr-4": {
            "" : ""
        }
    }
}

.htaccess(Apache)

RewriteEngine On
RewriteBase /

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?$1 [QSA,L]

.htaccess(Nginx)

rewrite ^/(.*)/$ /$1 redirect;

if (!-e $request_filename){
	rewrite ^(.*)$ /index.php break;
}