这是个好问题。我认为您对 MVC 和设计模式提供的关注点分离有点困惑。 (再次)看看 CakePHP 如何实现 MVC:http://book.cakephp.org/2.0/en/cakephp-overview/understanding-model-view-controller.html。
要记住的重要一点是,您的控制器永远不应该关心创建anchor 标签。这就是你的观点的工作。由于助手是一种让您的视图保持干燥(不要重复自己)的方法,因此唯一的责任就是创建 HTML 元素非常方便。视图依赖于控制器来确定设置了哪些变量、它们的值是什么以及加载了哪些帮助程序。有关 Helpers 以及控制器组件和模型行为的更多信息,请查看 http://book.cakephp.org/2.0/en/getting-started/cakephp-structure.html 以及它们各自的文档页面:
现在您对 MVC 有了更好的了解,让我们来看看您的具体问题。您想在控制器中创建链接。我认为它可能是动态的,取决于其他一些变量,所以我将继续使用它。
您可以解决的一个常见问题是根据用户是否已登录来显示登录/注销链接。
在 app/Controller/ExampleController.php
class ExampleController extends AppController {
public $components = array('Auth');
public $helpers = array('Html', 'Form');
public function beforeRender() {
parent::beforeRender();
//if Auth::user() returns `null` the user is not logged in.
if ($this->Auth->user() != null) {
$logInOutText = 'Log out';
$logInOutUrl = array('controller' => 'users', 'action' => 'login');
} else {
$logInOutText = 'Log in';
$logInOutUrl = array('controller' => 'users', 'action' => 'logout');
}
$this->set(compact('logInOutText', 'logInOutUrl'));
}
}
然后,您可以在您的视图中做一些简单的事情。在这种情况下,我选择默认布局,因为我想要 每个 呈现页面中的链接。 app/View/Layouts/default.ctp
<!-- More HTML above -->
<?php
// "Html" in `$this->Html` refers to our HtmlHelper. Note that in a view file
// like a `.ctp`, `$this` referes to the View object, while above in the
// controller `$this` refers to the Controller object. In the case
// `$this->Html`, "Html" would refer to a component. The same goes for Models
// and behaviors.
echo $this->Html->link($logInOutText, $logInOutUrl); // Easy!
?>
<!-- More HTML below -->
我希望这会有所帮助。我知道一次要完成很多工作。