juststeveking/uri-builder

PHP中一个简单的URI构建器,具有一定的观点

3.0.0 2022-07-15 11:40 UTC

This package is auto-updated.

Last update: 2024-09-15 16:21:27 UTC


README

URI Builder

Latest Version PHP Version tests Scrutinizer Code Quality Total Downloads

PHP中一个简单的URI构建器,具有一定的观点

目的

此包的目的是提供一个流畅的接口来构建符合JSON:API规范的URI字符串。

用法

使用PHP内建的parse_url会生成以下输出

[
    "scheme" => "https",
    "host" => "www.domain.com",
    "path" => "/api/v1/resource"
    "query" => "include=test,another&sort=-name",
]

这对于基本使用是足够的。要使用这个具有很强观点的包

实用构建

$url = Uri::build()
           ->addScheme('https')
           ->addHost('www.domain.com')
           ->addPath('api/v1/resource')
           ->addQuery('include=test,another&sort=-name')
           ->addFragment('static-link-to-element');

从字符串创建

$url = Uri::fromString('https://www.domain.com/api/v1/resource?include=test,another&sort=-name')

转换回字符串

$url = Uri::build()
           ->addScheme('https')
           ->addHost('www.domain.com')
           ->addPath('api/v1/resource')
           ->addQuery('include=test,another&sort=-name');

$string = $url->toString();

// optionally
echo (string) $url;

toString方法有一个可选参数,允许你在返回URI之前对查询参数进行urlencode。

$url = Uri::build()
           ->addScheme('https')
           ->addHost('www.domain.com')
           ->addPath('api/v1/resource')
           ->addQuery('include=test,another&sort=-name');

$string = $url->toString(true)

创建后添加查询参数

创建后添加查询参数非常简单。你可以传递任何不是

  • 对象
  • 数组

该函数末尾有一个辅助选项,可以将布尔值转换为字符串。

public function addQueryParam(string $key, $value, bool $covertBoolToString = false)

以下是它的用法

$url = Uri::fromString('https://www.domain.com/api/v1/resource');
$url->addQueryParam('include', 'test,another,options')
    ->addQueryParam('published', true, true);

输出将是:https://www.domain.com/api/v1/resource?include=test,another,options&published=true