Welcome Guest, Not a member yet? Register   Sign In
Recommended OO approach when using CI
#1

Sorry if I am driving people a little crazy with all the questions Huh  I am in the process of learning CI and want to try and do things the "correct" way from the start.

I come from a procedural background and I am trying hard to adopt a more OO approach.  This question might be more PHP related than it is CI related, I'm not sure.

Anyway, I am wondering what is the best approach when working with controllers and models in CI.  I see an awful lot of examples on the web like this:

PHP Code:
$this->load->model('customer_model');

$customer $this->customer_model->get(123); // Get the customer
$colours $this->customer_model->get_colours(123); // Get the customers favourite colours

echo $customer->email// Print their email address

// Print their favourite colours
foreach ($colours as $colour) {
 
   echo $colour;
}

$success $this->customer->save(123, array('email' => '[email protected]')); // Change their email address in the DB

if (!$success) {
 
  die('Something went wrong');


The above is an approach I am very familiar with, and seems similar to many of the examples I see in tutorials and so on.  However I can't help feeling a better approach is:

PHP Code:
$this->load->model('customer_model');

try {

 
   $this->customer_model->get(123); // Get the customer
 
   $this->customer_model->get_colours(123); // Get the customers favourite colours

 
   echo $this->customer_model->get_value('email'); // Print their email address

 
   // Print their favourite colours
 
   foreach ($this->customer_model->get_value('colours') as $colour) {
 
       echo $colour;
 
   }

 
   $this->customer_model->set_value('email''[email protected]'); // Change their email address

 
   $this->customer->save(); // Save their email address to the DB

 
   // Or even chaining:
 
   $this->customer_model->set_value('email''[email protected]')->save();

} catch (
Exception $e) {
 
   die$e->getMessage() );


Please let me know what you think. I appreciate your thoughts.
Reply


Messages In This Thread
Recommended OO approach when using CI - by CINewb - 05-11-2016, 05:16 PM



Theme © iAndrew 2016 - Forum software by © MyBB