Plugin: Modularity
Modularity: an easier way to access CodeIgniter objects
I’ve become sick and tired of CodeIgniter’s $this-centeredness in favor of an easier, globally-accessible way to access core CodeIgniter objects such as libraries, models, view, and db. So… here is a plugin!
- Eliminates need to call get_instance() when you need to access framework objects inside a model, library, helper, or view
- Bonus: auto-load libraries, models, databases
- Concise syntax
- Support for multiple database connections
- Requires PHP5 & CodeIgniter 1.5+
Installation
This is a plugin so no core hacking is required. Simply download modular_pi.zip (source) and extract it into your application/plugins folder. Load it just like any other plugin.
Using Modularity
Views
# Display a view -- old way
$this->load->view('myview', $data);
# new way
View::show('myview', $data);
# Load a view into a string variable -- old way
$pagetext = $this->load->view('myview', $data, TRUE);
# new way
$pagetext = View::parse('myview', $data);
Libraries
# Do something with a library -- old way
$this->load->library('mylibrary');
$this->library->do_something();
# new way
Libs('mylibrary')->do_something(); // the library automatically loads if needed
Models
# Fetch data with a model -- old way
$this->load->model('mydatamodel');
$this->mydatamodel->do_something();
# new way
Models('mydatamodel')->do_something(); // the model automatically loads if needed
Databases
# Query a database -- old way (default database)
$this->load->database();
$query = $this->db->query($sql);
# new way
$query = DB()->query($sql); // the database automatically loads if needed
# Query a database -- old way (multiple connections)
$dbh1 = $this->load->database('db1', TRUE);
$dbh2 = $this->load->database('db2', TRUE);
$query1 = $dbh1->query($sql);
$query2 = $dbh2->query($sql);
# new way
$query1 = DB('db1')->query($sql);
$query2 = DB('db2')->query($sql);
Inside libraries, helpers, or views
# old way
$CI =& get_instance();
$CI->load->model('mymodel');
$CI->mymodel->do_something();
# new way -- no calling get_instance()!
Models('mymodel')->do_something();
Really Nice, Thanks
Any new release coming soon?
Rewrite this for Codeigniter 2.0 and you’ll be reborn…
Was thinking about this while I was briefing a junior and talking about how cool it would have been if CI itself had some thing similar to this..
I came to your blog through a mysql related search, but this has been a neat bonus. As suggested above, will pair this up with CI2.0