生成URLs

Yii不仅允许你将URL路由到不同的控制器动作上,而且可以通过执行一个正确的内部路由和它的参数来生成一个URL。这非常有用,因为在开发应用过程中,你可以将精力集中在内部路由上,只需要在上线前关注一下真实的URL。永远不要直接指定URL,并确保你使用了Yii URL工具集。它会允许你修改URL,而且不需要修改很多应用代码。

准备

  1. 按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。
  2. 找到@app/config/web.php文件,并替换规则数组:
  1. 'urlManager' => array(
  2. 'enablePrettyUrl' => true,
  3. 'showScriptName' => false,
  4. ),
  1. 配置你的应用服务器来使用干净的URL。如果你在使用带有mod_rewrite的Apache,并打开了AllowOverride,那么你就可以添加如下内容到@app/web文件夹下的.htaccess文件中:
  1. Options +FollowSymLinks
  2. IndexIgnore */*
  3. RewriteEngine on
  4. # if a directory or a file exists, use it directly
  5. RewriteCond %{REQUEST_FILENAME} !-f
  6. RewriteCond %{REQUEST_FILENAME} !-d
  7. # otherwise forward it to index.php
  8. RewriteRule . index.php

如何做…

  1. @app/controllers目录中,使用如下代码创建BlogController
  1. <?php
  2. namespace app\controllers;
  3. use yii\web\Controller;
  4. class BlogController extends Controller
  5. {
  6. public function actionIndex()
  7. {
  8. return $this->render('index');
  9. }
  10. public function actionRssFeed($param)
  11. {
  12. return $this->renderContent('This is RSS feed for our blog and ' . $param);
  13. }
  14. public function actionArticle($alias)
  15. {
  16. return $this->renderContent('This is an article with alias ' . $alias);
  17. }
  18. public function actionList()
  19. {
  20. return $this->renderContent('Blog\'s articles here');
  21. }
  22. public function actionHiTech()
  23. {
  24. return $this->renderContent('Just a test of action which contains more than one words in the name') ;
  25. }
  26. }

这是我们的博客控制器,我们将会给它生成自定义URL。

  1. @app/controllers文件夹中,使用如下代码创建TestController
  1. <?php
  2. namespace app\controllers;
  3. use Yii;
  4. use yii\web\Controller;
  5. class TestController extends Controller
  6. {
  7. public function actionUrls()
  8. {
  9. return $this->render('urls');
  10. }
  11. }
  1. @app/views文件夹中,创建test文件夹,以及urls.php视图文件,文件内容如下:
  1. <?php
  2. use yii\helpers\Url;
  3. use yii\helpers\Html;
  4. ?>
  5. <h1>Generating URLs</h1>
  6. <h3>Generating a link with URL to <i>blog</i> controller and
  7. <i>article</i> action with alias as param</h3>
  8. <?= Html::a('Link Name', ['blog/article', 'alias' => 'someAlias']); ?>
  9. <h3>Current url</h3>
  10. <?=Url::to('')?>
  11. <h3>Current Controller, but you can specify an action</h3>
  12. <?=Url::toRoute(['view', 'id' => 'contact']);?>
  13. <h3>Current module, but you can specify controller and
  14. action</h3>
  15. <?= Url::toRoute('blog/article')?>
  16. <h3>An absolute route to blog/list </h3>
  17. <?= Url::toRoute('/blog/list')?>
  18. <h3> URL for <i>blog</i> controller and action <i>HiTech</i>
  19. </h3>
  20. <?= Url::toRoute('blog/hi-tech')?>
  21. <h3>Canonical URL for current page</h3>
  22. <?= Url::canonical()?>
  23. <h3>Getting a home URL</h3>
  24. <?= Url::home()?>
  25. <h3>Saving a URL of the current page and getting it for
  26. re-use</h3>
  27. <?php Url::remember()?>
  28. <?=Url::previous()?>
  29. <h3>Creating URL to <i>blog</i> controller and <i>rss-feed</i>
  30. action while URL helper isn't available</h3>
  31. <?=Yii::$app->urlManager->createUrl(['blog/rss-feed', 'param' => 'someParam'])?>
  32. <h3>Creating an absolute URL to <i>blog</i> controller and
  33. <i>rss-feed</i></h3>
  34. <p>It's very useful for emails and console applications</p>
  35. <?=Yii::$app->urlManager->createAbsoluteUrl(['blog/rss-feed', 'param' => 'someParam'])?>
  1. 打开http://yii-book.app/test/urls你将会看到如下输出(参考先前代码中全部方法的列表):

生成URLs - 图1

工作原理…

我们需要生成URL,指向BlogController的控制器动作(RssFeed, Article, List, HiTech)。

  1. <?= Html::a('Link Name', ['blog/article', 'alias' => 'someAlias']); ?>

依赖于我们需要的地方,有不同的方式可以做到这些,但是基础是一样的。下面列出一些生成URL的方法。

什么是内部路由?每一个控制器和它的动作有相应的路由。路由的格式是moduleID/controllerID/actionID。例如,BlogControlleractionHiTech方法对应于blog/hi-tech路由。

为了获取控制器ID,你应该用它的不带Controller后缀的名称,并将它的首字母小写。为了获取一个动作ID,你应该用它的不带action前缀的方法名,同样将每个单词的首字母小写,并使用-符号分割(例如actionHiTech将会是hi-tech)。

$_GET变量做为参数会被传递给用内部路由指定的动作中。例如,如果我们想为BlogController::actionArticle创建一个URL,并将$_GET['name']传递给它,可以按如下方式进行:

  1. <?= Html::a('Link Name', ['blog/article', 'alias' => 'someAlias']); ?>

在你的应用内部,可以使用相对URL,绝对URL应该被用于指向你的网站(例如其它网站)外部,或者用于链接到能被外部访问的资源上(RSS feeds,email等等)。

你可以很容易的使用URL管理器。URL管理器是一个内置应用组件,名叫urlManager。你必须使用这个组件,它可以通过Yii::$app->urlManager从web和console被访问到。

当你不能获得一个控制器实例时,例如,当你实施一个控制台应用,你可以使用如下两个urlManager创建方法:

  1. <?=Yii::$app->urlManager->createUrl(['blog/rss-feed', 'param' => 'someParam'])?>
  2. <?=Yii::$app->urlManager->createAbsoluteUrl(['blog/rss-feed','param' => 'someParam'])?>

更多…

欲了解更多信息,参考如下URL:

参考

  • 配置URL规则小节