I made a helper that returns the URL for a given page.
Helper file:
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;
}
(By the way, is there a variable I can use in place of http://www.domain.com such as full_site_url, base_url, etc?)
This is what my view looks like when I pass parameters to the helper:
<?php echo $this->Html->link($page['Page']['title'], $this->Custom->PageuRL($page['Page']['link'], $page['Category']['directory'], $page['Page']['id'])); ?>
This is a lot to write every time.
I created a component that fetches the URL of the page I want to go to. It is currently implement on AppController so I'm able to display the current page's URL fine, but I would like to use it inside the view or inside a helper to display another page's 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
With this way, I only need to pass one param to the component.
I know it is not good to use components inside of helpers and I'm not sure if it's even allowed in this version of CakePHP but it would make creating links much simpler. Does anyone know how I can either use this component in a helper or make a helper act in the same way where I only have to pass the page variable?
EDIT: Ok this is working for me and it may be frowned upon by everyone because it involves doing queries in the helper but it's really simplifying things. I'll see if it slows down my site.
I'm still open to suggestions on how to improve this.
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;
}