In actual projects, we recommend using the built-in URL tool class of Yii2 to generate links, because in this way we can very conveniently manage the URL behavior of the entire site: for example, changing the entire site by modifying the configuration URL format, etc.
Yii2 built-in URL generation tool
URL manager: urlManager
URL helper class: yii\helpers\Url
Using the built-in URL generation tool, you can beautify the URL of the entire site through configuration without changing the source code.
(Recommended tutorial: yii framework)
URL Manager
The URL manager is a built-in called urlManager Application components. In WEB applications and console applications, URLs can be created in the following two ways:
\Yii::$app->urlManager->createUrl($params) \Yii::$app->urlManager->createAbsoluteUrl($params, $schema = null)
createUrl method generates a relative path to the root directory, for example: /index.php?r=article/view
## The #createAbsoluteUrl() method generates an absolute path, for example: http://www.example.com/index.php?r=article/viewCommon examples of using URL managers to create URLs:// URL:/index.php?r=article/view \Yii::$app->urlManager->createUrl('article/view'); // URL:/index.php?r=article/view&id=2 \Yii::$app->urlManager->createUrl(['article/view','id'=>2]); // URL: http://www.example.com?r=kernel/article/viewecho \Yii::$app->urlManager->createAbsoluteUrl('kernel/article/view');
URL Helper Class
Compared with the URL manager, using the yii\helpers\Url helper class can greatly simplify the creation of URLs. 1. Assume that the current URL /index.php?r=kernel/article/view&id=10, the following explains how the URL helper class Url::to() works (not recommended): 2. Assume that the current URL /index.php?r=kernel/article/view&id=10, the following explains how the URL helper class Url::toRoute() method works (recommended) : 3. Assume that the current URL /index.php?r=kernel/article/view&id=10, the following explains how the URL helper class Url::current() method is Working (recommended): For more programming-related content, please pay attention to theIntroduction to Programming column on the php Chinese website!
The above is the detailed content of How to generate hyperlinks in yii framework. For more information, please follow other related articles on the PHP Chinese website!