What is the difference between a library and a model in the CodeIgniter Framework?

I am new to CI. Before I worked a lot in RoR and Symfony.

I cannot understand why CI provides the library and models. Most of the CI code that I reviewed usually used the library as a wrapper around the model. Models are designed exclusively for talking with the database.

Can someone shed some light on this?

+6
php codeigniter
source share
2 answers

There are probably other schools of thought, but for me it is:

Models

Models are closely related to your application, directly referring to your database / architecture / file path schemas, etc.

Libraries

Libraries are loosely coupled. They should be considered as third-party add-ons and no assumptions should be made about your application or your system. You should be able to "embed" libraries as you wish with minimal configuration. In fact, the opposite should be true, the items in the library folder should be deleted in any other CI application.

+17
source share

The Basques conceived in Libraries were a way of extending Codeigniter functions through classes.

If you compare the empty anatomy of the Library and the Model in Codeigniter, you will see that Models extend CI_MODEL , which allows you to access your own Codeigniter resources (for example $ this-> db).

Libraries do not offer this basic access, and they also do not need to be expanded through CI_MODEL .

Models are created for displaying and interacting with data (mainly abstracted from databases such as mysql).

Take a look at the main library

<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Library{ public function MyFunction(){ //do something... } } 

... and Model Anatomy

 <?php defined('BASEPATH') OR exit('No direct script access allowed'); class User_model extends CI_Model { public function __construct(){ parent::__construct(); } public function MyFunction(){ //do something... } } 

In most cases, Models are ready to use Ressources to access databases or other functions. There is no library. You need to enable or extend Ressources manually if you need it:

 //Create an CI instance $CI =& get_instance(); 

Libraries are collections of tools and feature extensions, and Models are ideal for abstracting and interacting with data coming from databases.

0
source share

All Articles