openclerk/routing

该包的最新版本(0.1.0)没有可用的许可信息。

PHP中的简单路由库

0.1.0 2017-09-11 07:41 UTC

This package is auto-updated.

Last update: 2024-09-14 09:38:21 UTC


README

PHP中的简单路由库。

使用

本项目使用openclerk/config进行配置管理。

首先使用特定于站点的值配置组件

Openclerk\Config::merge(array(
  "absolute_url" => "http://localhost/path/",
));

添加一个简单的路由文件

<?php
// router.php

require(__DIR__ . "/../inc/global.php");
$path = require_get("path", "security/login/password");

try {
  \Openclerk\Router::process($path);
} catch (\Openclerk\RouterException $e) {
  header("HTTP/1.0 404 Not Found");
  echo htmlspecialchars($e->getMessage());
}
?>

添加一个.htaccess文件,将路径转换为此路由器

RewriteEngine on

# Forbid access to any child PHP scripts
RewriteRule ^([^\.]+)/([^\.]+).php$   -                   [F]

RewriteRule ^([^\.]+)$                router.php?path=$1  [L,QSA]

定义站点路由

// set up routes
\Openclerk\Router::addRoutes(array(
  "security/login/password" => "security/login.php?type=password",
  "security/login/:key" => "security/login-:key.php?type=:key",
  // by default any unmatched routes will require <module>.php
));

现在您可以使用url_for()absolute_url_for()

<a href="<?php echo htmlspecialchars(url_for('security/login/password')); ?>">Login with password</a>

可渲染的对象

您还可以传递一个具有render($args)方法的对象,该方法的调用将代替上述方法

class MyApi {
  function render($args) {
    // $args = array('code' => ...)
  }
}

\Openclerk\Router::addRoutes(array(
  "api/currency/:code" => new MyApi(),
));

测试

composer update --dev
vendor/bin/phpunit

待办事项

  1. 实际文档
  2. 测试
  3. 在Packagist上发布