10

The way I create CodeIgniter models at the moment is (i.e. no constructor, having to pass userID all the time and limited to one object):

$this->load->model('User');
$this->user->set_password($userID, $password);

But I would like to do it like this:

$this->load->model('User');
$User = new User($userID);
$User->set_password($password);

UPDATE: Perhaps just a user model was a poor example.

For instance, if I have a shopping list that has various items I would like to use PHP in this way:

$this->load->model('List');
$this->load->model('Item');

$List = new List();
$items[] = new Item($itemName1, $itemPrice1);
$items[] = new Item($itemName2, $itemPrice2);

$List->add_items($items);

CodeIgniter feels fundamentally broken in handling PHP OO in this way. Does anyone have any solutions that can still use the superobject within every model?

4
  • 2
    Do you just favor using the new operator? Commented Dec 13, 2011 at 18:41
  • Codeigniter use one big superobject called CI. I don't think be a good idea add new objects to that framework. In any case they should be inherit from him. Commented Dec 13, 2011 at 18:49
  • I'd like to be able to store objects in other objects Commented Dec 13, 2011 at 19:16
  • You are not supposed to use the load-> function for every instance of every object in CI. It's only for application-level items. Nothing prevents you from creating your own object (library or model) and using require_once to make them available, then instantiating/using them however you wish. If you need access to the CI object, you can get it from anywhere by doing $CI =& get_instance(); Commented Dec 14, 2011 at 1:17

2 Answers 2

13

You can do it like you normally would:

require_once(APPPATH.'models/User.php');
$User = new User($userID);

Or, you can rely on a table-level model to return a record-level model:

$this->load->model('users_model'); // users (plural) is the table-level model
$User = $this->users_model->get_user($userID);

Meanwhile, in users_model

require_once(APPPATH.'models/User.php');

public function get_user($userID)
{
  // get a record from the db
  // map record to model
  // return model
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can subclass the model or just add something in the constructor I think you need to adjust code to do it the way you're looking to…

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.