[eluser]Andy Ingham[/eluser]
Matt,
Thanks for getting back on this.
Well, to use a simplified example, I'm reading through a database of products in my model and passing back to the controller an array of objects, each object holding one row from the database, e.g. getProducts() function in Products_model something like this:
Code:
$this->db->select('*');
$this->db->from('products as prod');
$this->db->join('categories as cat', 'cat.id = prod.category_id');
$query = $this->db->get();
return $query->result();
The controller calls the model and loops through the result and it can display the ID of each product item:
Code:
$products = $this->Products_model->getProducts();
foreach ($products as $product) {
echo 'Product ID: ' . $product->prod_id;
}
Now what if I have a method that I'd like to be available for each product item so that, for example, I could find out total value of stock (stock level * unit price), so I'd want to do something like this:
Code:
$products = $this->Products_model->getProducts();
foreach ($products as $product) {
echo 'Product ID: ' . $product->prod_id;
echo 'Stock Value: ' . $product->stockValue();
}
Obviously I'd need to create a productItem_model something like this:
Code:
class productItem_model extends CI_Model {
function __construct() {
parent::__construct();
}
function stockValue () {
return $this->stockLevel * $this->unitPrice;
}
}
So my question is can I get the CI
result() function to return results as an array of
productItem objects rather than just stdClass objects?
Assuming that I can't, then I presumably need to change the constructor function of my Product model so that it can receive a stdClass object as a parameter and then create attributes from that? This would mean something like the following:
Controller:
Code:
$products = $this->Products_model->getProducts();
foreach ($products as $stdClassObject) {
$product = new productItem_model($stdClassObject);
echo 'Product ID: ' . $product->prod_id;
echo 'Stock Value: ' . $product->stockValue();
}
productItem_model:
Code:
class productItem_model extends CI_Model {
function __construct($stdClassObject) {
parent::__construct();
foreach($stdClassObject as $attrib => $value) {
$this->$attrib = $value
}
}
function stockValue () {
return $this->stockLevel * $this->unitPrice;
}
}
I think that this will work (yet to test it out) but wondering whether it's the most elegant approach.
Andy