22 December, 2010

Dynamic functions in CodeIgniter Model

Using dynamic function can be of great ease at times. Since i was developing some project on codeIgniter, i thought of giving it a try to create dynamic functions in codeigniter model. The following code is just a startup, if this works out good then will add more of the functions in it.
Functions can be created on the fly using PHP's magic method __call(). As per php.net this method is triggered when invoking methods that are not accessible in object context.
So, in codeIgniter as there are controllers, views and models. I thought of adding a model that would create dynamic functions, which can then be accessed by controllers.
The code snippet is just a test.
I created a Test_model.php file as:

class Test_model extends Model {
private $id = 0;
private $table;
private $fields = array();
function Test_model() {
parent::Model();
}
//setup the tablename and field names
function set_up_table($table, $fields) {
$this->table = $table;
foreach($fields as $key) {
$this->fields[$key] = null;
}
}
//magic method to set and get
function __call($method, $args) {
if(preg_match("/set_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
$this->fields[$exists[1]] = $args[0];
return true;
}
}
else if(preg_match("/get_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
return $this->fields[$exists[1]];
}
}
return false;
}
//function to insert to database
function insert() {
$this->db->insert($this->table, $this->fields);
return $this->db->insert_id();
}

}

Now the controller part:

class Welcome extends Controller {

function Welcome() {
parent::Controller();
}

function index() {
//name of fields in book table
$fieldsArr = array( 'id', 'author','title', 'publisher' );
$tableName = "book";

$this->load->model("Test_model", "test");
$this->test->set_up_table($tableName, $fieldsArr);
$this->test->set_author("John Doe");
$this->test->set_title("Advanced PHP Web Development");
$this->test->set_publisher("Wrox");
$bookId = $this->test->insert();

$this->load->view('welcome_message');
}
}

And thats it. The code in controller sets values for all the fields and then we call insert function created in our model. The main objective behind the code is to show how dynamic functions tend to ease out the process of coding.