Professional CodeIgniter

(singke) #1

Chapter 3: A 10,000 - Foot View of CodeIgniter


65


‘featured’ ENUM (‘true’, ‘false’) NOT NULL,
‘price’ FLOAT( 4, 2 ) NOT NULL,
PRIMARY KEY ( ‘id’ )
) TYPE = MYISAM ;

The standard practice with CodeIgniter is to have one model for each database table, which gives you
(and any other developer on the team) easy access to a well - organized library of functions that relate to a
specific database table.

Because you ’ re just at the very beginning of the project, the best thing to do right now is to initialize your
models and put in the bare bones in each file. Bare bones in this context means adding two functions, one
that allows you to select a particular category or product and another that allows you to list all of them.

Updating the MProducts Model


First, create the model for categories. You can name your models anything you want, as long as the
names don ’ t conflict with each other or the names of your controllers. Standard practice indicates
putting some kind of prefix or suffix on a model filename to keep them distinct from controllers. Some
programmers use a suffix of _model , others use a prefix of m_. In this book, you ’ ll use a prefix of m on
your model files to keep things straight (e.g., mcats.php or mproducts.php ).

Once again, here ’ s a very basic model called MCats , with its PHP 4 constructor. Notice that this model,
like all models, extends the core CodeIgniter model.

class MCats extends Model{
function MCats(){
parent::Model();
}
}

As promised, you will now add two simple functions to this model. The first will retrieve one category
from the database:

function getCategory($id){
$data = array();
$options = array(‘id’ = > $id);
$Q = $this- > db- > getwhere(‘categories’,$options,1);
if ($Q- > num_rows() > 0){
$data = $Q- > row_array();
}

$Q- > free_result();
return $data;
}

This function passes in an $id variable that is used to select one (and only one) row matching that ID
from the categories table. It then returns the data as an array for future use.
Free download pdf