Professional CodeIgniter

(singke) #1

Chapter 4: Creating the Main Web Site


91


function cat(){
$cat = $this- > MCats- > getCategory($this- > uri- > segment(3));
if (!count($cat)){
redirect(‘welcome/index’,’refresh’);
}
$data[‘title’] = “Claudia’s Kids | “. $cat[‘name’];

if ($cat[‘parentid’] < 1){
//show other categories
}else{
//show products

}
$data[‘category’] = $cat;
$data[‘main’] = ‘category’;
$data[‘navlist’] = $this- > MCats- > getCategoriesNav();
$this- > load- > vars($data);
$this- > load- > view(‘template’);
}

The first thing the function does is use the getCategory() function to retrieve the category in question.
How does it know to do that? Because you ’ re passing in a category ID inside the URI. Specifically, the third
URI segment contains the category ID, and you use the $this - > uri - > segment() method to do that.


If you have security on your mind, you might have noticed that no validation is being done when the
URI segment is grabbed. At the very least, you should be making sure this value is an integer of a
certain length. Never fear, this site won ’ t go live without some kind of validation at this level. In
Chapter 9 , you learn more about these kinds of security issues. Here, just learn how to use the tools.

A simpler way of grabbing the URI segment is to simply pass in the expected ID as an argument to the
function, as :

function cat($id){
$cat = $this- > MCats- > getCategory($id);
if (!count($cat)){
redirect(‘welcome/index’,’refresh’);
}
$data[‘title’] = “Claudia’s Kids | “. $cat[‘name’];

if ($cat[‘parentid’] < 1){
//show other categories
}else{
//show products

}
$data[‘category’] = $cat;
$data[‘main’] = ‘category’;
$data[‘navlist’] = $this- > MCats- > getCategoriesNav();
$this- > load- > vars($data);
$this- > load- > view(‘template’);
}

This approach is much cleaner and makes it easier to map incoming URI segments to functional pieces of
your code. You use this syntax throughout the project.
Free download pdf