Welcome Guest, Not a member yet? Register   Sign In
Loading a model without instantiating (OOP support in CI)
#1

[eluser]beardedlinuxgeek[/eluser]
I think this a pretty common situation. You have a model class and some other classes that extend that class. In this case we have a few different types of vehicles, each with an ID in the database.

Code:
class Vehicle extends CI_Model {

var $id;
var $model;
var $color;


function __construct ( $vehicle_id ) {
  parent::__construct();

  $vehicle = $this->db->get_where( 'vehicle', array('id' => $vehicle_id) )->row();
  foreach ( $vehicle as $property => $value ) {
   $this->$property = $value;
  }
}


function schedule maintenance ( $date ) {
  // Schedule maintenance
}

}

class Car extends Vehicle {

function drive () {
  // Drive the car
}

}


class Helicopter extends Vehicle {

function fly () {
  // Fly the helicopter
}

}

I want to create my car I can just do
Code:
$car5 = new Car(5);
and my code is going to connect to the database and load up all the details for that car.

But when I do
Code:
$this->load->model('vehicle');
in the controller I get an error (obviously) for not having enough parameters because it loads the vehicle class into the CI super class without an id.

I could do something like
Code:
function __construct ( $vehicle_id = null ) {
if ( empty($vehicle_id) ) return;
but it feels clunky and hackish and I know for a fact I'll never call the model directly because
Code:
$this->vehicle->schedule_maintenance('Friday');
doesn't make sense without having created a vehicle object.

One thing I was thinking of doing is creating a new folder called "objects" and not having the Vehicle class extend CI_Model at all. But then I'd need to create a new function like
Code:
function set_db( $db ) {
$this->db = $db;
}

and then create my car from the controller like
Code:
$car5 = new Car(5);
$car5->set_db( $this->db );

which really isn't a bad idea from an Inversion of Control perspective. But I also only have one database and only plan on having one, so the benefit from this IoC is really minimal. And let say I decide I need to send an email to the guy doing the maintenance, now I need to load the email class and do
Code:
$this->load->library('email');

$car5 = new Car(5);
$car5->set_db( $this->db );
$car5->set_email_handler( $this->email );
and you can see how this gets out of hand quickly. It's great from an IoC perspective, but I just feel like managing dependency injection of the core CodeIgniter classes isn't really that useful.

Advice?


Messages In This Thread
Loading a model without instantiating (OOP support in CI) - by El Forum - 09-19-2012, 04:42 PM



Theme © iAndrew 2016 - Forum software by © MyBB