Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use proper object-oriented models in CodeIgniter with constructors?

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?

like image 506
Matt Votsikas Avatar asked Dec 13 '11 18:12

Matt Votsikas


People also ask

What is CI_Model in CodeIgniter?

The basic prototype for a model class is this: class Model_name extends CI_Model { } Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.

How can you add or load a model in CodeIgniter?

If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload. php file and adding the model to the autoload array.

How do I make a ci3 model?

Create a User. php file in application/controllers directory. Load above created Main_model using $this->load->model('Main_model') method in the __construct() method and call getUsers() method using $this->Main_model->getUsers() . Store the return response in a $data variable.

How to create a model in CodeIgniter 4?

Creating Your Model. To take advantage of CodeIgniter's model, you would simply create a new model class that extends CodeIgniter\Model : <? php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model { // ... }


1 Answers

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
}
like image 134
minboost Avatar answered Oct 04 '22 15:10

minboost