Welcome Guest, Not a member yet? Register   Sign In
custom class/model advice
#1

[eluser]Unknown[/eluser]
Hello,

I'm working on building classes and using CI to access it - basically I just want to use the CI database driver - and then I'm going to put my control logic in the controllers. But I'm not sure where to put my "business" logic.

example - I'm working on a shipping notification interface. I have orders that have items and I would like them to be nice objects (eg, $order->isComplete(), $order->hasShipping(), etc.)

for the time being I've created a model and put my logic in there:
Code:
$this->load->model('order');
$order = $this->Order;
$order->setParameters($init_data);
So far this has worked fine - the problem is that I want to do things like
Code:
$all_orders = $order->getAllOrders();
and have it return an array of objects.

I've run into a big of a snag in that inside my order model I haven't figured out how to return objects - and I'm starting to feel if I'm pounding a round peg in a square hole.

Can anyone give advice on how to do this - should I be building "libraries" instead of models?

Thanks,

yehosef
#2

[eluser]tonanbarbarian[/eluser]
I am not sure why you have to return an array of objects
I prefer to return my data from models as arrays rather than objects

If you want to return the action model class, I do not do things that way. I fell that the model should only return data and nothing else.

So I use models like this...
In the controller I load the model as normal (slightly differently to you)
Code:
$this->load->model('order');
Then if I want just a single known record I have a method in the model that retrieves the row
Code:
$orderRow = $this->order->load($id);
or if I want to get multiple
Code:
$allOrders = $this->order->getAll();
the code in the model can be very simple
Code:
class Order extends Model {

  function Order() {
    parent::Model();
  }

  function load($id) {
    $query = $this->db->getwhere('order', 'id='.(int)$id);
    return $query->row_array();
  } // load()

  function getAll() {
    $query = $this->db->get('order');
    return $query->result_array();
  } // getAll()

} // class Order

Models are the best way to implement this sort of Business Logic.
I tend to use Libraries to do thing that are needed in multiple controllers. My Libraries do sometimes load models to get the data they need

Oh and not sure if this is a typo or a bug, but the following line you have in your example code will not work
Code:
$order = $this->Order;
After you load the order model it is created as a property of the controller, but the property is always lowercase
Code:
$order = $this->order;
would work better
however the safest way to do it would be
Code:
$order =& $this->Order;
because the reference means any changes made to $order from then on are reference correctly throughout
personally I just stick with
Code:
$this->order...
instead as it is easier




Theme © iAndrew 2016 - Forum software by © MyBB