Welcome Guest, Not a member yet? Register   Sign In
Do I use a model, library or helper?
#4

[eluser]noslen1[/eluser]
Models are intended to be used for manipulating data in your database.
If you want to create an object class with variables and functions, I think you should create a library like so :
/libraries/Product.php
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Product {
    var $title = '';
    var $price = 0;
    var $description = '';

    public function __construct(){
        // Constructor function called each time you create a new product
    }
    
    public function calculate_new_price(){
        
    }
}

You can use also a Model as mentionned by egy_programozo to retrieve data from database, for instance :
/models/products_model.php
Code:
<?php
class Products_model extends CI_Model{
    function get($id)  {
        $this->query = $this->db->select('title, price, description')
            ->from('db_products')
            ->where('id', $id)
            ->limit(1)
            ->get();

        return $this->query->row();
    }
}

And call both into your controller :
/controllers/products.php
Code:
$this->load->model('products_model');
$this->load->library('product');

// Retrieve database data from your model
$my_product = $this->products_model->get($product_id);
// Set your data to your object variables
$this->product->title = $my_product->title
$this->product->price = $my_product->price
$this->product->description = $my_product->description
// Call a function to do what you want
$this->product->price = $this->product->calculate_new_price();

This would be a bit cleaner I guess, but more code as well.


Messages In This Thread
Do I use a model, library or helper? - by El Forum - 10-17-2012, 08:37 AM
Do I use a model, library or helper? - by El Forum - 10-17-2012, 02:23 PM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 01:22 AM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 01:34 AM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 01:41 AM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 02:05 AM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 02:11 AM
Do I use a model, library or helper? - by El Forum - 10-18-2012, 02:33 AM



Theme © iAndrew 2016 - Forum software by © MyBB