The Model is responsible for managing the data of the application. It receives user input from the Controller. It can contain functions to insert, update, and retrieve your application data.
Model classes reside in the Models directory. They can be nested within sub-directories.
The basic syntax for the model is:
<?php namespace App\Models; use CodeIgniter\Model; use CodeIgniter\DatabaseConnectionInterface; class Model_name extends Model { protected $db; public function __construct(ConnectionInterface &$db) { $this->db =& $db; } } ?>
Let’s see the following example for a better understanding of the model:
<?php namespace App\Models; use CodeIgniter\Model; use CodeIgniter\DatabaseConnectionInterface; class BlogModel extends Model { protected $db; public function __construct(ConnectionInterface &$db) { $this->db =& $db; } public function add() { $data = [ 'title' => 'Title', 'description' => 'Description' ]; return $this->db ->table('blog_info') ->insert($data); } public function get_blog_list() { return $this->db ->table('blog_info') ->where(["status" => "1"]) ->get() ->getResult(); } }?>
The file name must match the class name and the first letter of the Model class must be a capital letter.
How to load a Model in a Controller?
use App\Models\model_name;
Initialize constructor:
public function __construct() { $db = db_connect(); $this->model = new model_name($db); }
If your model is located in a sub-directory, include the relative path from your model’s directory. For example, if you have a model located at /app/Models/user/Profile.php you’ll load it using the:
use AppModelsuserProfile; public function __construct() { $db = db_connect(); $this->profileModel = new Profile($db); }
Once the model is loaded, you can access all the public methods using an object with the same name as your class:
$this->profileModel>method();
Here is an example of a controller, that loads a model, then serves a view:
<?php namespace App\Controllers; use App\Controllers\BaseController; use AppModelsBlogModel; class Blog extends BaseController { public function __construct() { $db = db_connect(); $this->blogModel = new BlogModel($db); } public function index() { $data[‘list’] = $this->blogModel>get_blog_list(); echo view('about_us', $data); } } ?>
Methods Comparison in CodeIgniter 4 vs CodeIgniter 3
CodeIgniter 3 | CodeIgniter 4 |
---|---|
insert(); | insert(); |
delete(); | delete(); |
update(); | update(); |
row(); | getRow(); |
result(); | getResult(); |