Welcome Guest, Not a member yet? Register   Sign In
Use object oriented programming in CI
#1

Hello, 

my name is Akis and I've just sign up the forum but I'm not new in CI. I love this framework. I'm using it for 5 years now and I think I will be using it for many years more. I'm exciting for being informed that CI 4 is about to released ...

Since now I write code without using oop logic in my project (ofcourse except the CI core logic which is object oriented). I just use cmv model without write any class: in controller files I manage the data, in model file I have my sqls and in view files I have the output.

I'm never wrote any fully object oriented project in any program language or framework but I'm familiar with it.

The fact is that I'm not sure how I can use oop logic in CI. Let me use an example to deploy my thinking. Let's say we have the following simple db schema:

Office
  id
  floor
  number
  descr

Employee
  id
  name
  sirname
  office_id (foreign key)


In oop I would created two classes for these two tables. The code below is the class for Office:

Class Office {
  public $id, $floor, $number, $descr

  // Construct method without any param
  function __construct() {
    // code
  }

  // Overloading construct method using param to get the data from db for a specific office
  function __construct($office_id) {
    // Reference to model file (sqls.php)
    $office_details = $this->sqls->get_office($office_id);

    $id = $office_details['id'];
    $floor = $office_details['floor'];
    $number = $office_details['number'];
    $descr = $office_details['descr'];
  }

  // Add office in DB method
  public addOffice {
    // Reference to model file (sqls.php)
    $new_id = $this->sqls->add_office();
  }

  // Delete office from DB method
  public deleteOffice($office_id) {
    // Reference to model file (sqls.php)
    $this->sqls->delete_office($office_id);
  }

  ...
}

Since I'm done with writing all Classes, I imagine that I must import the file that contains all classes into the controller file. Lets say I want to  show in a html table all the offices. Should I create as many objects of Office class as the number of the rows in db table 'Office' like below?
 
// Reference to model file (sqls.php)
$offices = $this->sqls->get_offices();

foreach ($offices as $o) {
  $office_object = new Office($o['id']);

  // pass data to view file via $data variable
  $data[$o['id']]['floor'] = $office_object->floor;
  $data[$o['id']]['number'] = $office_object->number;
  $data[$o['id']]['descr'] = $office_object->descr;
}


Is my way of thinking right?? Because it seems logically wrong to create so many objects. I dont know if I'm right. 

Is there a better way to use oop in CI? 

Thank you very much
Akis
Reply


Messages In This Thread
Use object oriented programming in CI - by akisthess79 - 09-13-2016, 01:38 AM



Theme © iAndrew 2016 - Forum software by © MyBB