keppler/url

URL操作

v2.1.0 2018-12-18 20:36 UTC

This package is auto-updated.

Last update: 2024-09-04 20:16:35 UTC


README

Build Status Software License Documentation Status Maintainability Scrutinizer Code Quality

阅读文档文档

安装

composer require keppler/url

快速入门

解析器和构建器

此包分为2个独立的组件。这些组件也进一步分为几个其他组件。

The Scheme.php will be referred to as Parser in the documentation.

解析器

解析器是解析URL的入口点。它是不可变的,意味着一旦创建就无法更改。

方案被分为ftp、http、https、mailto等方案。每个方案用于解析单一URL类型,正如你可能猜测的那样。

require 'vendor/autoload.php';

$url =  'https://john.doe@www.example.com:123/forum/questions/answered/latest?tag=networking&order=newest#top';

$scheme = Scheme::https($url);

print_r($scheme->all());

echo $scheme->getPathBag()->first(); // forum
echo $scheme->getPathBag()->last(); // latest
echo $scheme->getPathBag()->raw(); // /forum/questions/answered/latest
echo $scheme->getPathBag()->get(1); // questions
echo $scheme->getPathBag()->has(0); // true
echo $scheme->getPathBag()->has(10); // false


var_dump($scheme->getQueryBag()->first()); // ['tag' => 'networking']

etc

在撰写本文时,解析器支持4种方案:FTP、HTTPS、HTTP和MAILTO

构建器

Builder.php类是修改URL或从头开始创建一个URL的入口点。如果你选择从一个现有的URL开始构建,你必须传递一个具有适当方案的解析器实例。

在撰写本文时,构建器支持4种方案:FTP、HTTPS、HTTP和MAILTO

require 'vendor/autoload.php';

$url =  'ftp://user:password@host:123/path';

$ftpScheme = Scheme::ftp($url);
$builder = Builder::ftp($ftpScheme);

$builder->setHost('example.com')
    ->setPassword('hunter2')
    ->setPort(5);

print_r($builder->raw());
...
ftp://user:hunter2@example.com:5/path/

print_r($builder->encoded());
...
ftp://user:hunter2@example.com:5/path/to+encode/ // notice the extra +

解析器和构建器都可以独立使用。

每个支持的方案也可以在没有构建器或解析器的情况下独立使用。以下是一些示例。

独立使用

假设你不想直接使用解析器/构建器类,你可以选择不使用。

每个支持的方案都可以独立于解析器/构建器使用。

$ftpUrl = 'ftp://user:password@host:123/path';

$ftpImmutable = new FtpImmutable($ftpUrl);

echo $ftpImmutable->raw();

$ftpBuilder = new FtpBuilder();

$ftpBuilder->setHost('host')
    ->setPassword('hunter2')
    ->setPort(987)
    ->setUser('hunter');

$ftpBuilder->getPathBag()
    ->set(0, 'path')
    ->set(1, 'new path');

echo $ftpBuilder->raw(); // ftp://hunter:hunter2@host:987/path/new path/

echo $ftpBuilder->encoded(); // ftp://hunter:hunter2@host:987/path/new+path/