Named Scopes with CodeIgniter

codeigniter, database, models, php

Named scopes are a really powerful feature of models - they allow you to define a clean, concise syntax when performing queries within your models - and best of all, are really easy to utilise in CodeIgniter.

The main principle of a named scope is that you create a method that, combined with method chaining, allows you to add details to your query (generally additional WHERE clauses). This can make the selection syntax a lot nicer to use, turning something complicated and messy like:

Into something nice, clear and readable, like this:

Of course, this is a bit of a psuedo-code mockup - in reality, you’d not interface with CodeIgniter’s ActiveRecord like I did in the first example, you’d create some method in your model to perform the entire find, or better still, use my MY_Model Library.

But what if you want to use both (or either) - the bolt-on filtering style of named scopes and/or the base model presets. Using named scopes doesn’t really require any trickery - and once they’re created, you can use them for pretty much anything.

This is probably sounding a little bit cryptic - let me clear this up with some nice code. Take, for example, this model. It is extending from my aforementioned MY_Model Library.

Because of the MY_Model Library, it already has a load of basic CRUD methods implemented. Now, we could build up the previous find using a custom method and directly return the result of db->get(), or we could combine the two.

So now we’ve got two named scopes, one that restricts the query depending on a level column in the database and one that adds some default ordering and limiting (judging by the name this function would generally be called whenever we lookup users). We’re returning $this after each named scope. That way, using the magic of method chaining we can then call any other methods to perform the actual query - we could nick the database object and run get(‘users’) or we could be even flashier and use the get_all() method in the MY_Model.

The same principle works if you’re not using the MY_Model. You just return $this->db, or return $this and implement your own finder methods in the model.

I’m sure I’ll revisit named scopes at some point on this blog; they’re a powerful and downright sexy way of scoping your model queries.