Part 2 -Creating the application database model.
Now that we are done the CI installation. We are ready to start building our e-commerce application. What we need to do first is design our database structure. You can of course freely design your own structure, but for this tutorial I made it simple.Now, Let say,
I want to categorize my products. So we must have a table for category.
Product category can have a child category.
Category can be deactivated and activated.
This is our table for categories looks like.
- CREATE TABLE `categories` (
- `cat_id` int(11) NOT NULL auto_increment,
- `cat_name` varchar(255) NOT NULL,
- `cat_shortdesc` varchar(255) NOT NULL,
- `cat_longdesc` text NOT NULL,
- `cat_parentid` int(11) NOT NULL,
- `cat_status` tinyint(1) NOT NULL,
- PRIMARY KEY (`cat_id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Can only belong to one category at a time
Our products has a name, image, thumbnail, short description, long description
And can be activated and deactivated.
This is what I came up with our products table.
- CREATE TABLE `products` (
- `prod_id` int(11) NOT NULL auto_increment,
- `prod_name` varchar(255) NOT NULL,
- `prod_shortdesc` varchar(255) NOT NULL,
- `prod_longdesc` text NOT NULL,
- `prod_thumbnail` varchar(255) NOT NULL,
- `prod_image` varchar(255) NOT NULL,
- `prod_status` tinyint(1) NOT NULL,
- `prod_category_id` int(11) NOT NULL,
- `prod_featured` tinyint(1) NOT NULL,
- `prod_price` float(4,2) NOT NULL,
- PRIMARY KEY (`prod_id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Creating the Categories Model
In creating a model in CodeIgniter you can name it anything you want as long as it don’t have any conflicts of names in other model or to your controller. It is a good practice to put a prefix or suffixes to your model’s name. My style in naming a model is chosen name suffixed by‘Model’
. So I have to name our model to ‘categoryModel’
.More details about creating model can be read in CI userguide. Now let’s create our basic model called
categoryModel
and our constructor.- <?php
- class categoryModel extends Model{
- function categoryModel(){
- parent::Model();
- }
- }
categorymodel.php
in your system/application/models/
directory.Then add a function that will retrieve a category from the database.
- function getCategory($id){
- $data = array();
- $where = array('cat_id' => $id);
- $quer = $this->db->getwhere('categories',$where,1);
- if ($query-> num_rows() > 0){
- $data = $query->row_array();
- }
- $query->free_result();
- return $data;
- }
$id
variable that is used to select one row matching that ID from the categories table. It then returns the data as an array for future use.Now we can select our category one by one with the function we just made. Next we have to create a function that returns all the categories in our categories table.
- function getAllCategories(){
- $data = array();
- $query = $this->db->get('categories');
- if ($query->num_rows() > 0){
- foreach($query->result_array() as $row){
- $data[] = $row;
- }
- }
- $query-> free_result();
- return $data;
- }
Your
categorymodel.php
should look like this now.- <?php
- class categoryModel extends Model{
- function categoryModel(){
- parent::Model();
- }
- function getCategory($id){
- $data = array();
- $where = array('cat_id' => $id);
- $query = $this->db->getwhere('categories',$where,1);
- if ($query-> num_rows() > 0){
- $data = $query->row_array();
- }
- $query->free_result();
- return $data;
- }
- function getAllCategories(){
- $data = array();
- $query = $this->db->get('categories');
- if ($query->num_rows() > 0){
- foreach($query->result_array() as $row){
- $data[] = $row;
- }
- }
- $query-> free_result();
- return $data;
- }
- }
Creating the Products Model
Now create a new file name itproductsmodel.php
in your /system/application/models/
folder. And copy the code below.- <?php
- class productsModel extends Model{
- function productsModel(){
- parent::Model();
- }
- function getProduct($id){
- $data = array();
- $where = array('prod_id' => $id);
- $query = $this->db->getwhere('products',$where,1);
- if ($query-> num_rows() > 0){
- $data = $query-> row_array();
- }
- $query->free_result();
- return $data;
- }
- function getAllProducts(){
- $data = array();
- $query = $this-> db-> get('products');
- if ($query-> num_rows() > 0){
- foreach ($query-> result_array() as $row){
- $data[] = $row;
- }
- }
- $query-> free_result();
- return $data;
- }
- }
As we go ahead later on this series maybe we need to add more functions to this models like for example a function that will retrieved all the products by a category id. But that’s it for now.
Now we need to auto load our models so that it will be available globally and saves us time in loading it locally in our controller. To do so, open the file
/system/application/config/autload.php
. Find $autoload
option and add the following line.- $autoload['model'] = array('categoryModel', 'productsModel');
- $autoload['libraries'] = array('database');
For the categories table.
- INSERT INTO `ci_tutorial`.`categories` (
- `cat_id` ,
- `cat_name` ,
- `cat_shortdesc` ,
- `cat_longdesc` ,
- `cat_parentid`
- )
- VALUES
- ('1', 'Photo Books', 'This is a photo books', 'This is a long description of the photo book category.', '0'),
- ('2', 'Photo Calendar', 'This is a photo calendar', 'This is a long description of the Photo Calendar category.', '0'),
- ('3', 'Photo Tumblers', 'This is a photo Tumbler', 'This is a long description of the photo tumbler category.', '0'),
- ('4', 'Photo Magnets', 'This is a photo magnets', 'This is a long description of the Photo magenets category.', '0');
- INSERT INTO `products` (`prod_id`, `prod_name`, `prod_shortdesc`, `prod_longdesc`, `prod_thumbnail`, `prod_image`, `prod_status`, `prod_category_id`, `prod_featured`, `prod_price`) VALUES
- (1, 'Large Hard Cover Photo Book', 'Short Description of Large Hard Cover Photo Book', 'Long Description of Large Hard Cover Photo Book', '/uploads/products/thumb/lhc-photo-books.jpg', '/uploads/products/lhc-photo-books.jpg', 1, 1, 1, 20.50),
- (2, 'Desktop Tumbler', 'Short Description Desktop Tumbler', 'Long Description Desktop Tumbler', '/uploads/products/thumb/d-tumbler.jpg', '/uploads/products/d-tumbler.jpg', 1, 3, 0, 15.23);
- <?php
- class test extends Controller {
- function test()
- {
- parent::Controller();
- $this->load->library('parser');
- }
- function index()
- {
- $data['title'] = 'Building an e-commerce application using CodeIgniter ';
- $data['header'] = 'Header of the Test Page';
- $data['body'] = 'Test content here. Another content gooes here.';
- $id = '1'; //sample value of cat_id
- //test our category model
- $myCat = $this->categoryModel->getCategory($id);
- $data['myCat'] = $myCat['cat_name'];
- $data['allCategory'] = $this->categoryModel->getAllCategories();
- //test our product model
- $myProduct = $this->productsModel->getProduct($id);
- $data['myProduct'] = $myProduct['prod_name'];
- $data['allProducts'] = $this->productsModel->getAllProducts();
- $this->parser->parse('test_page', $data);
- }
- }
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
- <title>Untitled Document</title>
- </head>
- <body>
- <h4>A Category With an ID of 1</h4>
- <p>{myCat}</p>
- <h4>All Category List</h4>
- <ul>
- <?php foreach($allCategory as $cat){?>
- <li>
- <?= $cat['cat_name']; ?>
- </li>
- <?php } ?>
- </ul>
- <hr />
- <h4>A Product With an ID of 1</h4>
- <p>{myProduct}</p>
- <h4>All Product List</h4>
- <ul>
- <?php foreach($allProducts as $product){?>
- <li>
- <?= $product['prod_name']; ?>
- </li>
- <?php } ?>
- </ul>
- </body>
- </html>
http://localhost/tutorial/
. Since we have to view our test controller, type this url http://localhost/tutorial/test/
You must now see a list of categories and products we just have inserted lately to our database.
No comments:
Post a Comment