v3.0.0 2024-03-25 09:34 UTC

README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.4+ Supports PHP 8.0+ Latest Stable Version

统一资源标识符(URI)是一串字符,用于标识抽象或物理资源。

  foo://example.com:8042/over/there?name=ferret#nose
  \_/   \______________/\_________/ \_________/ \__/
   |           |            |            |        |
scheme     authority       path        query   fragment
   |   _____________________|__
  / \ /                        \
  urn:example:animal:ferret:nose

参见https://tools.ietf.org/html/rfc3986

示例

从字符串解析

最常见的情况是从给定的输入字符串构建URI。

use util\URI;

$uri= new URI('https://user:password@localhost:8443/index?sort=name#top');
$uri->isOpaque();     // false - it's a hierarchical URI
$uri->scheme();       // "https"
$uri->authority();    // util.Authority("localhost", 8443, "user", util.Secret("password"))
$uri->host();         // "localhost"
$uri->port();         // 8443
$uri->user();         // "user"
$uri->password();     // util.Secret("password")
$uri->path();         // "index"
$uri->query();        // "sort=name"
$uri->params();       // util.URIParameters("sort=name")
$uri->param('sort');  // "name"
$uri->fragment();     // "top"

创建或修改

URI实例是不可变的。然而,通过with()using()提供了一个流畅的接口。两者都返回新的实例。

use util\URI;

$uri= URI::with()->scheme('mailto')->path('timm@example.com')->param('Subject', 'Hello')->create();
$uri->isOpaque();   // true - it's an opaque URI
$uri->scheme();     // "mailto"
$uri->authority();  // null
(string)$uri;       // "mailto:timm@example.com?Subject=Hello"

$copy= $uri->using()->path('cc@example.com')->create();
(string)$copy;      // "mailto:cc@example.com?Subject=Hello"

解析URI

给定http://localhost/home/作为基本URI,您可以使用resolve()方法在其上下文中解析链接。

use util\URI;

$uri= new URI('http://localhost/home/');
$uri->resolve('/index.html');       // util.URI<http://localhost/index.html>
$uri->resolve('index.html');        // util.URI<http://localhost/home/index.html>
$uri->resolve('?sort=name');        // util.URI<http://localhost/home/?sort=name>
$uri->resolve('#top');              // util.URI<http://localhost/home/#top>
$uri->resolve('//example.com');     // util.URI<http://example.com>
$uri->resolve('https://localhost'); // util.URI<https://localhost>

文件系统

URI可以指向文件系统路径。两者之间的转换并不简单——您需要正确处理Windows UNC路径。URI类的file()asPath()方法负责处理这些问题。

use util\URI;

$uri= URI::file('/etc/php.ini');
(string)$uri;       // "file:///etc/php.ini"

$uri= new URI('file://c:/Windows');
$uri->path();       // "C:/Windows"
$uri->asPath();     // io.Path("C:\Windows")

$uri= new URI('file://share/file.txt');
$uri->authority();  // util.Authority("share")
$uri->path();       // "/file.txt"
$uri->asPath();     // io.Path("\\share\file.txt")