I wrote a post a few days ago about a new change in CodeIgniter Reactor, which allows people to clean up their models. Today I’m going to go a bit further and talk about how we can use static context to really make our models awesome. Lets look at the same example as in the last post, but implemented a little differently:

<?php
class User extends CI_Model {
  private static $db;
  function __construct() {
    parent::__construct();
    self::$db = &get_instance()->db;
  }
  static function get_by_email_address($email) {
    return self::$db->where('email', $email)->get('users')->result('User');
  }
  function comments() {
    $this->load->model('comment');
    return $this->db->where('user_id', $this->id)->get('comments')->result('Comment');
  }
}
<?php
class Comment extends CI_Model {
  function __construct() {
    parent::__construct();
  }
}

It’s really nice because now the methods that should be static, are kept totally separate from the instance methods. This makes everything super clean, and we’re able to abuse CodeIgniter’s creation of a single instance (created via $this->load) to get the equivelant of a static initializer block (to do things like setting the value of the convenience self::$db variable). Check out how its used:

<?php
$this->load->model('user');
$user = User::get_by_email_address('john.crepezzi@gmail.com');
// print all of the comments by the user
echo "<h2>Comments by $user->name</h2>";
foreach ($user->comments() as $comment) {
  echo "<p>$comment->body</p>";
}

Writing models like this will make your experience working with CI ActiveRecord really positive, and keeping the seperation will make your mind happy and your IDE happy.