10

I am new to CI. Before I had worked extensively in RoR and Symfony.

I am unable to understand why exactly CI provides Library and Models. Most of the CI code I examined generally used Library as a Wrapper around Model. Models are exclusively kept for talking to database.

Can someone throw light on this ?

2 Answers 2

21

There are probably other schools of thought on this, but for me it's as follows:

Models

Models are tightly coupled to your application, making direct references to your DB schema/architecture/file paths etc.

Libraries

Libraries are loosely coupled. They should be treated like 3rd party add-ons and should make no assumptions about your app or your system. You should be able to "drop in" libraries at will with a minimum amount of configuration. Indeed, the opposite should be true, items in your library folder should be able to be dropped into any other CI application.

Sign up to request clarification or add additional context in comments.

2 Comments

With reference to your view on library, I thought the said functionality was achieved through "modules" in CI.
@Akshar There is some overlap in concepts at times, but a library can be thought of as a singleton class that is mostly (if not fully) independent of that particular CI application. There are no strict rules as to what you can do with a library, but if you want an idea of what a library should do, take a look at some of the native CI libraries, like the image_lib.
2

The basci thought on Libraries was a way to extend Codeigniter's functionality through classes.

If you compare the blank anatomy of a Library and a Model in Codeigniter, you will see that Models extend the CI_MODEL which allows you to access Codeigniter's native resources (for Example $this->db).

Libraries do not offer that basic access and they also do not need to be extended through the CI_MODEL.

Models are made to depict and interact with data (mostly abstracted from databases such as mysql).

Take a look at the basic Library

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

...and the 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 the Models are prepared to use Ressources to access databases or other functionalities. Libraries don't. You need to include or extend the Ressources manually if you need them:

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

Libraries are tool collections and function extensions while Models are natively ideal for abstracting and interacting with data coming from databases.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.