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


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:
$order = $this->Order;
So far this has worked fine - the problem is that I want to do things like
$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?



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)
Then if I want just a single known record I have a method in the model that retrieves the row
$orderRow = $this->order->load($id);
or if I want to get multiple
$allOrders = $this->order->getAll();
the code in the model can be very simple
class Order extends Model {

  function Order() {

  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
$order = $this->Order;
After you load the order model it is created as a property of the controller, but the property is always lowercase
$order = $this->order;
would work better
however the safest way to do it would be
$order =& $this->Order;
because the reference means any changes made to $order from then on are reference correctly throughout
personally I just stick with
instead as it is easier

Theme © iAndrew 2016 - Forum software by © MyBB