Lavorare con gli URL
Le classi Url, UrlImmutable e UrlScript consentono di generare, analizzare e manipolare facilmente gli URL.
Url
La classe Nette\Http\Url consente di lavorare facilmente con gli URL e i suoi singoli componenti, catturati in questo diagramma:
scheme user password host port path query fragment | | | | | | | | /--\ /--\ /------\ /-------\ /--\/----------\ /--------\ /----\ http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer \______\__________________________/ | | hostUrl authority
La generazione di URL è intuitiva:
use Nette\Http\Url;
$url = new Url;
$url->setScheme('https')
->setHost('localhost')
->setPath('/edit')
->setQueryParameter('foo', 'bar');
echo $url; // 'https://localhost/edit?foo=bar'
È anche possibile analizzare un URL e manipolarlo ulteriormente:
$url = new Url(
'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);
La classe Url
implementa l'interfaccia JsonSerializable
e ha un metodo __toString()
,
quindi l'oggetto può essere stampato o utilizzato nei dati passati a json_encode()
.
echo $url;
echo json_encode([$url]);
Componenti URL
Per restituire o modificare i singoli componenti dell'URL, sono disponibili i seguenti metodi:
Setter | Getter | Valore restituito |
---|---|---|
setScheme(string $scheme) |
getScheme(): string |
'http' |
setUser(string $user) |
getUser(): string |
'john' |
setPassword(string $password) |
getPassword(): string |
'xyz*12' |
setHost(string $host) |
getHost(): string |
'nette.org' |
setPort(int $port) |
getPort(): ?int |
8080 |
getDefaultPort(): ?int |
80 |
|
setPath(string $path) |
getPath(): string |
'/en/download' |
setQuery(string|array $query) |
getQuery(): string |
'name=param' |
setFragment(string $fragment) |
getFragment(): string |
'footer' |
getAuthority(): string |
'nette.org:8080' |
|
getHostUrl(): string |
'http://nette.org:8080' |
|
getAbsoluteUrl(): string |
intero URL |
Attenzione: Quando si lavora con un URL ottenuto da una HTTP request, tenere presente che non conterrà il frammento, poiché il browser non lo invia al server.
Possiamo anche lavorare con i singoli parametri query usando:
Setter | Getter |
---|---|
setQuery(string|array $query) |
getQueryParameters(): array |
setQueryParameter(string $name, $val) |
getQueryParameter(string $name) |
getDomain (int $level = 2): string
Restituisce la parte destra o sinistra dell'host. Funziona così se l'host è www.nette.org
:
getDomain(1) |
'org' |
getDomain(2) |
'nette.org' |
getDomain(3) |
'www.nette.org' |
getDomain(0) |
'www.nette.org' |
getDomain(-1) |
'www.nette' |
getDomain(-2) |
'www' |
getDomain(-3) |
'' |
isEqual (string|Url $anotherUrl): bool
Verifica se due URL sono identici.
$url->isEqual('https://nette.org');
Url::isAbsolute (string $url): bool
Verifica se l'URL è assoluto. Un URL è considerato assoluto se inizia con uno schema (es. http, https, ftp) seguito da due punti.
Url::isAbsolute('https://nette.org'); // true
Url::isAbsolute('//nette.org'); // false
Url::removeDotSegments (string $path): string
Normalizza il percorso nell'URL rimuovendo i segmenti speciali .
e ..
. Il metodo rimuove gli
elementi superflui del percorso nello stesso modo in cui lo fanno i browser web.
Url::removeDotSegments('/path/../subtree/./file.txt'); // '/subtree/file.txt'
Url::removeDotSegments('/../foo/./bar'); // '/foo/bar'
Url::removeDotSegments('./today/../file.txt'); // 'file.txt'
UrlImmutable
La classe Nette\Http\UrlImmutable è
un'alternativa immutabile alla classe Url (simile a come DateTimeImmutable
è l'alternativa
immutabile a DateTime
in PHP). Invece dei setter, ha i cosiddetti wither, che non modificano l'oggetto, ma
restituiscono nuove istanze con il valore modificato:
use Nette\Http\UrlImmutable;
$url = new UrlImmutable(
'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);
$newUrl = $url
->withUser('')
->withPassword('')
->withPath('/cs/');
echo $newUrl; // 'http://nette.org:8080/cs/?name=param#footer'
La classe UrlImmutable
implementa l'interfaccia JsonSerializable
e ha un metodo
__toString()
, quindi l'oggetto può essere stampato o utilizzato nei dati passati a json_encode()
.
echo $url;
echo json_encode([$url]);
Componenti URL
Per restituire o modificare i singoli componenti dell'URL, servono i seguenti metodi:
Wither | Getter | Valore restituito |
---|---|---|
withScheme(string $scheme) |
getScheme(): string |
'http' |
withUser(string $user) |
getUser(): string |
'john' |
withPassword(string $password) |
getPassword(): string |
'xyz*12' |
withHost(string $host) |
getHost(): string |
'nette.org' |
withPort(int $port) |
getPort(): ?int |
8080 |
getDefaultPort(): ?int |
80 |
|
withPath(string $path) |
getPath(): string |
'/en/download' |
withQuery(string|array $query) |
getQuery(): string |
'name=param' |
withFragment(string $fragment) |
getFragment(): string |
'footer' |
getAuthority(): string |
'nette.org:8080' |
|
getHostUrl(): string |
'http://nette.org:8080' |
|
getAbsoluteUrl(): string |
intero URL |
Il metodo withoutUserInfo()
rimuove user
e password
.
Possiamo anche lavorare con i singoli parametri query usando:
Wither | Getter |
---|---|
withQuery(string|array $query) |
getQueryParameters(): array |
withQueryParameter(string $name, $val) |
getQueryParameter(string $name) |
getDomain (int $level = 2): string
Restituisce la parte destra o sinistra dell'host. Funziona così se l'host è www.nette.org
:
getDomain(1) |
'org' |
getDomain(2) |
'nette.org' |
getDomain(3) |
'www.nette.org' |
getDomain(0) |
'www.nette.org' |
getDomain(-1) |
'www.nette' |
getDomain(-2) |
'www' |
getDomain(-3) |
'' |
resolve (string $reference): UrlImmutable
Deriva un URL assoluto nello stesso modo in cui il browser elabora i link su una pagina HTML:
- se il link è un URL assoluto (contiene uno schema), viene utilizzato senza modifiche
- se il link inizia con
//
, viene preso solo lo schema dall'URL corrente - se il link inizia con
/
, viene creato un percorso assoluto dalla radice del dominio - negli altri casi, l'URL viene costruito relativamente al percorso corrente
$url = new UrlImmutable('https://example.com/path/page');
echo $url->resolve('../foo'); // 'https://example.com/foo'
echo $url->resolve('/bar'); // 'https://example.com/bar'
echo $url->resolve('sub/page.html'); // 'https://example.com/path/sub/page.html'
isEqual (string|Url $anotherUrl): bool
Verifica se due URL sono identici.
$url->isEqual('https://nette.org');
UrlScript
La classe Nette\Http\UrlScript è un discendente di UrlImmutable e lo estende con ulteriori componenti URL virtuali, come la directory radice del progetto, ecc. Come la classe genitore, è un oggetto immutabile.
Il seguente diagramma mostra i componenti che UrlScript riconosce:
baseUrl basePath relativePath relativeUrl | | | | /---------------/-----\/--------\---------------------------\ http://nette.org/admin/script.php/pathinfo/?name=param#footer \_______________/\________/ | | scriptPath pathInfo
baseUrl
è l'URL di base dell'applicazione, inclusi il dominio e la parte del percorso alla directory radice dell'applicazionebasePath
è la parte del percorso alla directory radice dell'applicazionescriptPath
è il percorso allo script correnterelativePath
è il nome dello script (eventualmente altri segmenti del percorso) relativo a basePathrelativeUrl
è l'intera parte dell'URL dopo baseUrl, inclusi query string e frammento.pathInfo
è una parte dell'URL, oggi poco utilizzata, dopo il nome dello script
Per restituire parti dell'URL, sono disponibili i seguenti metodi:
Getter | Valore restituito |
---|---|
getScriptPath(): string |
'/admin/script.php' |
getBasePath(): string |
'/admin/' |
getBaseUrl(): string |
'http://nette.org/admin/' |
getRelativePath(): string |
'script.php' |
getRelativeUrl(): string |
'script.php/pathinfo/?name=param#footer' |
getPathInfo(): string |
'/pathinfo/' |
Gli oggetti UrlScript
di solito non li creiamo direttamente, ma vengono restituiti dal metodo Nette\Http\Request::getUrl() con i componenti già correttamente impostati per
la richiesta HTTP corrente.