Codeigniter – The Perfect Model

In this screencast, will explore different ways to access data from your codeigniter models. We’ll start by writing SQL from scratch and refactor our models until our code is safe against sql injection, database agnostic, and DRY. We’ll wrap up the screencast by taking a quick look at PHP ActiveRecord.

References:
PHP ActiveRecord
Matthew Machuga’s Blog
CI Sparks Package Manager
PHP ActiveRecord Spark

As a side note, here’s a quick start if you’d like to develop your own master model.

<?php

class MY_Model extends CI_Model {

  public $table;
  
  public function __construct()
  {
    parent::__construct();
    $this->load->database();
  }

  public function find()
  {
    return $this->db->get($this->table)->result();
  }
  
  public function find_by_id($id)
  {
    return $this->db->where('id', $id)->limit(1)->get($this->table)->row();
  }

  public function insert($data)
  {
    $this->db->set($data);
    $this->db->insert($this->table);
    return $this->db->insert_id();
  }

  public function update($id, $data)
  {
    $this->db->where('id', $id);
    $this->db->set($data);
    $this->db->update($this->table);
    return $this->db->affected_rows()
  }
  
  public function delete($id)
  {
    $this->db->where('id', $id);
    $this->db->delete();
    return $this->db->affected_rows()
  }
}
Advertisements

2 thoughts on “Codeigniter – The Perfect Model

  1. Thank you for the tutorial. It’s great for beginner like me. Your way of teching is to the point and easy to follow. Please make another episode for this screencast series. A great thanks to you again.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s