Lavorare con gli URL
********************
.[perex]
Le classi [#Url], [#UrlImmutable] e [#UrlScript] permettono di generare, analizzare e manipolare facilmente gli URL.
→ [Installazione e requisiti |@home#Installazione]
Url
===
La classe [api:Nette\Http\Url] permette di manipolare facilmente gli URL e le loro singole componenti, come illustrato in questo diagramma:
/--pre
scheme user password host port path query fragment
| | | | | | | |
/--\ /--\ /------\ /-------\ /--\/----------\ /--------\ /----\
<b>http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer</b>
\______\__________________________/
| |
hostUrl authority
\--
Generare gli URL è intuitivo:
```php
use Nette\Http\Url;
$url = new Url;
$url->setScheme('https')
->setHost('localhost')
->setPath('/edit')
->setQueryParameter('foo', 'bar');
echo $url; // 'https://localhost/edit?foo=bar'
```
Potete anche analizzare un URL e poi manipolarlo:
```php
$url = new Url(
'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);
```
La classe `Url` implementa l'interfaccia `JsonSerializable` e ha il metodo `__toString()`, quindi l'oggetto si può stampare o usare nei dati passati a `json_encode()`.
```php
echo $url;
echo json_encode([$url]);
```
Componenti dell'URL
-------------------
Per ottenere o modificare le singole componenti dell'URL sono disponibili questi metodi:
.[language-php]
| 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` | `'john:xyz%2A12@nette.org:8080'`
| | `getHostUrl(): string` | `'http://john:xyz%2A12@nette.org:8080'`
| | `getAbsoluteUrl(): string` | URL completo
I metodi `getUser()`, `getPassword()`, `setUser()` e `setPassword()` sono deprecati, perché inserire le credenziali direttamente nell'URL è sconsigliato.
Attenzione: quando lavorate con un URL ottenuto da una [richiesta HTTP |request], tenete presente che non conterrà il frammento, perché il browser non lo invia al server.
Possiamo lavorare anche con i singoli parametri della query:
.[language-php]
| Setter | Getter
|---------------------------------------------------
| `setQuery(string\|array $query)` | `getQueryParameters(): array`
| `setQueryParameter(string $name, $val)` | `getQueryParameter(string $name)`
| `appendQuery(string|array $query)` |
getDomain(int $level = 2): string .[method]
-------------------------------------------
Restituisce la parte destra o sinistra dell'host. Ecco come funziona se l'host è `www.nette.org`:
.[language-php]
| `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 $url): bool .[method]
----------------------------------------
Verifica se due URL sono identici.
```php
$url->isEqual('https://nette.org');
```
canonicalize() .[method]
------------------------
Converte l'URL in forma canonica. Converte il nome host in minuscolo e normalizza il percorso (percent-encoding e rimozione dei caratteri superflui). La query string resta invariata.
Url::isAbsolute(string $url): bool .[method]{data-version:3.3.2}
----------------------------------------------------------------
Verifica se un URL è assoluto. Un URL è considerato assoluto se inizia con uno schema (per esempio http, https, ftp) seguito da due punti.
```php
Url::isAbsolute('https://nette.org'); // true
Url::isAbsolute('//nette.org'); // false
```
Url::removeDotSegments(string $path): string .[method]{data-version:3.3.2}
--------------------------------------------------------------------------
Normalizza il percorso di un URL rimuovendo i segmenti speciali `.` e `..`. Questo metodo rimuove gli elementi superflui del percorso nello stesso modo dei browser web.
```php
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 [api:Nette\Http\UrlImmutable] è l'alternativa immutabile alla classe [#Url] (in modo 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:
```php
use Nette\Http\UrlImmutable;
$url = new UrlImmutable(
'https://nette.org:8080/en/download?name=param#footer',
);
$newUrl = $url
->withHost('example.com')
->withPath('/en/')
->withQueryParameter('name', 'value');
echo $newUrl; // 'https://example.com:8080/en/?name=value#footer'
```
La classe `UrlImmutable` implementa l'interfaccia `JsonSerializable` e ha il metodo `__toString()`, quindi l'oggetto si può stampare o usare nei dati passati a `json_encode()`.
```php
echo $url;
echo json_encode([$url]);
```
Componenti dell'URL
-------------------
Per ottenere o modificare le singole componenti dell'URL sono disponibili questi metodi:
.[language-php]
| 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` | `'john:xyz%2A12@nette.org:8080'`
| | `getHostUrl(): string` | `'http://john:xyz%2A12@nette.org:8080'`
| | `getAbsoluteUrl(): string` | URL completo
I metodi `getUser()`, `getPassword()`, `withUser()`, `withPassword()` e `withoutUserInfo()` sono deprecati, perché inserire le credenziali direttamente nell'URL è sconsigliato.
Possiamo lavorare anche con i singoli parametri della query:
.[language-php]
| Wither | Getter
|-----------------------------------------------
| `withQuery(string\|array $query)` | `getQueryParameters(): array`
| `withQueryParameter(string $name, $val)` | `getQueryParameter(string $name)`
getDomain(int $level = 2): string .[method]
-------------------------------------------
Restituisce la parte destra o sinistra dell'host. Ecco come funziona se l'host è `www.nette.org`:
.[language-php]
| `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 .[method]{data-version:3.3.2}
----------------------------------------------------------------------
Risolve un URL assoluto nello stesso modo in cui un browser elabora i link di una pagina HTML:
- se il link è un URL assoluto (contiene lo schema), viene usato invariato
- 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
```php
$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 $url): bool .[method]
----------------------------------------
Verifica se due URL sono identici.
```php
$url->isEqual('https://nette.org');
```
UrlScript
=========
La classe [api:Nette\Http\UrlScript] è discendente di [#UrlImmutable] e la estende con altre componenti virtuali dell'URL, per esempio la directory radice del progetto ecc. Come la classe genitore è un oggetto immutabile.
Il diagramma seguente mostra le componenti che UrlScript riconosce:
/--pre
baseUrl basePath relativePath relativeUrl
| | | |
/---------------/-----\/--------\---------------------------\
<b>http://nette.org/admin/script.php/pathinfo/?name=param#footer</b>
\_______________/\________/
| |
scriptPath pathInfo
\--
- `baseUrl` è l'URL di base dell'applicazione, compresi il dominio e la parte di percorso fino alla directory radice dell'applicazione
- `basePath` è la parte di percorso fino alla directory radice dell'applicazione
- `scriptPath` è il percorso dello script corrente
- `relativePath` è il nome dello script (ed eventualmente altri segmenti di percorso) relativo a `basePath`
- `relativeUrl` è tutta la parte di URL dopo `baseUrl`, compresi query string e frammento
- `pathInfo` è la parte di URL dopo il nome dello script, oggi usata di rado
Per ottenere queste parti dell'URL sono disponibili questi metodi:
.[language-php]
| Getter | Valore restituito
|------------------------------------------------
| `getScriptPath(): string` | `'/admin/script.php'`
| `getBasePath(): string` | `'/admin/'`
| `getBaseUrl(): string` | `'http://nette.org/admin/'`
| `getRelativePath(): string` | `'script.php/pathinfo/'`
| `getRelativeUrl(): string` | `'script.php/pathinfo/?name=param#footer'`
| `getPathInfo(): string` | `'/pathinfo/'`
Di solito non creiamo direttamente gli oggetti `UrlScript`; li restituisce invece il metodo [Nette\Http\Request::getUrl() |request] con le componenti già impostate correttamente per la richiesta HTTP corrente.
Lavorare con gli URL
Le classi Url, UrlImmutable e UrlScript permettono di generare, analizzare e manipolare facilmente gli URL.
→ Installazione e requisiti
Url
La classe Nette\Http\Url permette di manipolare facilmente
gli URL e le loro singole componenti, come illustrato 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
Generare gli URL è intuitivo:
use Nette\Http\Url;
$url = new Url;
$url->setScheme('https')
->setHost('localhost')
->setPath('/edit')
->setQueryParameter('foo', 'bar');
echo $url; // 'https://localhost/edit?foo=bar'
Potete anche analizzare un URL e poi manipolarlo:
$url = new Url(
'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer',
);
La classe Url implementa l'interfaccia JsonSerializable e ha il metodo __toString(),
quindi l'oggetto si può stampare o usare nei dati passati a json_encode().
echo $url;
echo json_encode([$url]);
Componenti dell'URL
Per ottenere o modificare le singole componenti dell'URL sono disponibili questi 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 |
'john:xyz%2A12@nette.org:8080' |
| |
getHostUrl(): string |
'http://john:xyz%2A12@nette.org:8080' |
| |
getAbsoluteUrl(): string |
URL completo |
I metodi getUser(), getPassword(), setUser() e setPassword() sono
deprecati, perché inserire le credenziali direttamente nell'URL è sconsigliato.
Attenzione: quando lavorate con un URL ottenuto da una richiesta HTTP,
tenete presente che non conterrà il frammento, perché il browser non lo invia al server.
Possiamo lavorare anche con i singoli parametri della query:
| Setter |
Getter |
setQuery(string|array $query) |
getQueryParameters(): array |
setQueryParameter(string $name, $val) |
getQueryParameter(string $name) |
| `appendQuery(string |
array $query)` |
getDomain (int $level = 2): string
Restituisce la parte destra o sinistra dell'host. Ecco come funziona 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 $url): bool
Verifica se due URL sono identici.
$url->isEqual('https://nette.org');
canonicalize()
Converte l'URL in forma canonica. Converte il nome host in minuscolo e normalizza il percorso (percent-encoding e rimozione dei
caratteri superflui). La query string resta invariata.
Url::isAbsolute (string
$url): bool
Verifica se un URL è assoluto. Un URL è considerato assoluto se inizia con uno schema (per esempio 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 di un URL rimuovendo i segmenti speciali . e ... Questo metodo rimuove gli
elementi superflui del percorso nello stesso modo dei 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 è l'alternativa
immutabile alla classe Url (in modo 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(
'https://nette.org:8080/en/download?name=param#footer',
);
$newUrl = $url
->withHost('example.com')
->withPath('/en/')
->withQueryParameter('name', 'value');
echo $newUrl; // 'https://example.com:8080/en/?name=value#footer'
La classe UrlImmutable implementa l'interfaccia JsonSerializable e ha il metodo
__toString(), quindi l'oggetto si può stampare o usare nei dati passati a json_encode().
echo $url;
echo json_encode([$url]);
Componenti dell'URL
Per ottenere o modificare le singole componenti dell'URL sono disponibili questi 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 |
'john:xyz%2A12@nette.org:8080' |
| |
getHostUrl(): string |
'http://john:xyz%2A12@nette.org:8080' |
| |
getAbsoluteUrl(): string |
URL completo |
I metodi getUser(), getPassword(), withUser(), withPassword() e
withoutUserInfo() sono deprecati, perché inserire le credenziali direttamente nell'URL è sconsigliato.
Possiamo lavorare anche con i singoli parametri della query:
| 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. Ecco come funziona 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
Risolve un URL assoluto nello stesso modo in cui un browser elabora i link di una pagina HTML:
- se il link è un URL assoluto (contiene lo schema), viene usato invariato
- 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 $url): bool
Verifica se due URL sono identici.
$url->isEqual('https://nette.org');
UrlScript
La classe Nette\Http\UrlScript è discendente di UrlImmutable e la estende con altre componenti virtuali dell'URL, per esempio la directory radice del
progetto ecc. Come la classe genitore è un oggetto immutabile.
Il diagramma seguente mostra le 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, compresi il dominio e la parte di percorso fino alla directory radice
dell'applicazione
basePath è la parte di percorso fino alla directory radice dell'applicazione
scriptPath è il percorso dello script corrente
relativePath è il nome dello script (ed eventualmente altri segmenti di percorso) relativo
a basePath
relativeUrl è tutta la parte di URL dopo baseUrl, compresi query string e frammento
pathInfo è la parte di URL dopo il nome dello script, oggi usata di rado
Per ottenere queste parti dell'URL sono disponibili questi metodi:
| Getter |
Valore restituito |
getScriptPath(): string |
'/admin/script.php' |
getBasePath(): string |
'/admin/' |
getBaseUrl(): string |
'http://nette.org/admin/' |
getRelativePath(): string |
'script.php/pathinfo/' |
getRelativeUrl(): string |
'script.php/pathinfo/?name=param#footer' |
getPathInfo(): string |
'/pathinfo/' |
Di solito non creiamo direttamente gli oggetti UrlScript; li restituisce invece il metodo Nette\Http\Request::getUrl() con le componenti già impostate correttamente per
la richiesta HTTP corrente.