I’m just beginning to learn CodeIgniter so I picked up this book. As someone who has written PHP for years I find the introduction to CodeIgniter libraries, helpers and so on helpful. However, the code for the mock project is horribly written, overly simplified in some places and unnecessarily complicated in others. An example of over simplification is that he only uses one controller for an entire website. Anyone who uses this book as their only reference is going to think that they need a 170+ line controller file controlling their whole site.
An example of where it’s overly complex is this gem I ran into in Chapter 4 where he writes a function to find show 3 (Represented by ‘$limit’) random products that are not the same as the featured product (Represented by ‘$skip’) :
function getRandomProducts($limit,$skip){
$data = array();
$temp = array();
if ($limit == 0){
$limit=3;
}
$this->db->select("id,name,thumbnail,category_id");
$this->db->where('id !=', id_clean($skip));
$this->db->orderby("category_id","asc");
$this->db->limit(100);
$Q = $this->db->get('products');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$temp[$row['category_id']] = array(
"id" => $row['id'],
"name" => $row['name'],
"thumbnail" => $row['thumbnail']
);
}
}
shuffle($temp);
if (count($temp)){
for ($i=1;$i<=$limit; $i++){
$data[] = array_shift($temp);
}
}
$Q->free_result();
return $data;
}
The Limit 100 means that if site ever exceeds 100 products that none of those products (101 and up) will ever be shown on the front page. I feel like he’s way too reliant on the Active Record class. The same thing could easily be accomplished with a better query without bringing a second array into the function.
function getRandomProducts($limit,$skip){
$data = array();
$sql = 'SELECT `id`, `name`, `thumbnail`, `category_id` FROM `products` WHERE `id`!="' . $skip . '"
GROUP BY `category_id` ORDER BY rand() LIMIT ' . $limit;
$Q = $this->db->query($sql);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = array(
"id" => $row['id'],
"category_id" => $row['category_id'],
"name" => $row['name'],
"thumbnail" => $row['thumbnail']
);
}
}
$Q->free_result();
return $data;
}
I’d file it in the Errata section on wrox.com.. but the form asks way too many personal questions. Plus, I’m sure it would be rejected since technically his method works… even if it is dumb.