Home >Backend Development >PHP Tutorial >Joomla tip: Use the Joomla\Uri\Uri class to create a URL.
When building URLs in code, you can use string concatenation to collect all strings:
<code class="language-php">$url = $domain.'/index.php?option='.$option.'&view='.$view.'¶m1='.$value1;</code>
This approach is even convenient for short strings. However, it is not so convenient and intuitive if there are many parameters or need to be standardized/cleaned in the process. For example, part of the URL might contain a leading slash (the slash at the beginning of the URL fragment), and the incoming domain name of the request might also end in a slash, so we get a bad URL with a double slash somewhere in the middle ……
To standardize and unify URL retrieval tasks, Joomla provides the JoomlaUriUri class. In Joomla 1.6 and earlier, it was called JUri. This class handles URLs according to the RFC3986 standard and is responsible for parsing or assembling URLs from their various parts.
<code class="language-php">use Joomla\Uri\Uri; $url = 'https://web-tolk.ru/dev/biblioteki?param=value'; $uri = new Uri($url); // 此处输出'value' echo $uri->getVar('param');</code>
You might say, yes, there is a native PHP function parse_url
... but the Uri class ensures safe operations on UTF-8 characters in URLs, including Cyrillic domain names. To avoid writing various checks yourself, you can use Joomla core functionality.
It’s also very simple here:
<code class="language-php">use Joomla\Uri\Uri; $uri = new Uri; $uri->setHost('web-tolk.ru'); $uri->setScheme('https'); // setPath()以前导斜杠开头 $uri->setPath('/dev/biblioteki'); // GET参数可以作为数组传递 $vars = [ 'param1' => 'value1', 'param2' => 'value2', 'param3' => 'value3', ]; $uri->setQuery($vars); // 将URL作为字符串输出 echo $uri->toString();</code>
The hierarchical structure of the Uri class in Joomla is designed so that the getter method is located in the AbstractUri class, and the setter method is located in the Uri class. You can view the setter method in the libraries/vendor/joomla/uri/src/Uri.php file. You can view the getter method in the libraries/vendor/joomla/uri/src/AbstractUri.php file.
If you use PHPStorm, it understands Joomla completely and will tell you everything you need.
You can refer to the old documentation page, which is still applicable to a large extent and has been adapted for the use of namespaces.
Uri structure:
<code> foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment</code>
The above is the detailed content of Joomla tip: Use the Joomla\Uri\Uri class to create a URL.. For more information, please follow other related articles on the PHP Chinese website!