[英]CakePHP 2.2.4: Help Simply Links using Component/Helper
我做了一个帮助程序,它返回给定页面的URL。
助手文件:
public function PageURL($link = null, $category = null, $page = null){
if($link){
$link = strtolower(str_replace(' ', '-', $link));
$page_url = "http://www.domain.com/$link";
}
else{
$page_url = "http://www.domain.com/$category/$page";
}
return $page_url;
}
(顺便说一句,是否有一个变量可以代替http://www.domain.com使用,例如full_site_url,base_url等?)
这是我将参数传递给助手时的视图:
<?php echo $this->Html->link($page['Page']['title'], $this->Custom->PageuRL($page['Page']['link'], $page['Category']['directory'], $page['Page']['id'])); ?>
每次都要写很多东西。
我创建了一个组件,该组件可获取要访问的页面的URL。 它目前是在AppController上实现的,因此我可以很好地显示当前页面的URL,但是我想在视图内部或帮助器内部使用它来显示另一个页面的URL。
public function TestPageURL($page = null) {
App::uses('ClassRegistry', 'Utility');
$pagesModel = ClassRegistry::init('Page');
$matchedpage = $pagesModel->find('first', array(
'conditions' => array('Page.id' => $page), 'recursive' => '0'
));
if($matchedpage['Page']['link']){
$pagelink = strtolower(str_replace(' ', '-', $matchedpage['Page']['link']));
$page_url = "http://www.domain.com/" . $pagelink;
}
else{
$page_url = "http://www.domain.com/" . $matchedpage['Page']['Category']['directory'] . $matchedpage['Page']['id'];
}
return $page_url;
} // end page url
通过这种方式,我只需要将一个参数传递给组件。
我知道在助手中使用组件不是很好,并且我不确定在此版本的CakePHP中是否甚至允许使用它,但这会使创建链接变得更加简单。 有谁知道我该如何在帮助程序中使用此组件,或者以仅传递page变量的相同方式使帮助程序起作用?
编辑:好的,这对我有用,并且可能会引起每个人的反对,因为它涉及在帮助程序中进行查询,但实际上是在简化事情。 我会看看它是否会使我的网站慢下来。
我仍然愿意就如何改进它提出建议。
public function TestPageURL($page = null) {
$pagesModel = ClassRegistry::init('Page');
$matchedPage = $pagesModel ->find('first', array(
'conditions' => array('Page.id' => $page), 'recursive' => '1'
));
if($matchedPage ['Page']['link']){
$link = strtolower(str_replace(' ', '-', $matchedPage['Page']['link']));
$page_url = "http://www.domain.com/$link";
}
else{
$page_url = "http://www.domain.com/" . $matchedPage['Page']['Category']['directory'] . '/' .$matchedPage['Page']['id'];
}
return $page_url;
}
我建议在控制器中获取数据时在模型中创建URL。 顺便说一句,您可以使用Router::url
检索完整的基本URL。
示例(未试用)...型号:
public function findPagesIncludingURLs()
{
$pages = $this->find('all'); // or whatever you want to retreive
$base = Router::url('/', true);
foreach($pages as &$page)
{
$url = null;
if($page['Page']['link'])
{
$url = strtolower(str_replace(' ', '-', $page['Page']['link']));
}
else
{
$url = $page['Page']['Category']['directory'] . '/' . $page['Page']['id'];
}
$page['Page']['url'] = $base . $url;
}
return $pages;
}
控制器:
$this->set('pages', $this->Page->findPagesIncludingURLs());
视图:
echo $this->Html->link($page['Page']['title'], $page['Page']['url']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.