Created
December 6, 2010 03:18
-
-
Save walesmd/729784 to your computer and use it in GitHub Desktop.
CodeIgniter extended Model Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if (!defined('BASEPATH')) exit('No direct script access allowed.'); | |
/* MY_Model | |
* Reorganizes the $DB::result() object passed to it so joined | |
* tables are child-objects of the result object, rather than | |
* first-class variables. Pretty strict on the way it works. | |
* | |
* Example: | |
* protected $relationships = array( | |
* 'has_one' => array( | |
* 'company' | |
* ) | |
* ); | |
* | |
* function get() { | |
* $this->db->select('users.*') | |
* ->select('companies.name AS company_name') | |
* ->from('users') | |
* ->join('companies', 'companies.id = users.company_id'); | |
* $query = $this->db->get(); | |
* | |
* if ($query->num_rows($result) > 0) { | |
* return $this->_objectify($query->result()); | |
* } | |
* | |
* return NULL; | |
* } | |
*/ | |
class MY_Model extends CI_Model { | |
private $_result; | |
public function __construct() { | |
parent::__construct(); | |
} | |
/* _objectify() | |
* Reformats the result object so foreign keys are child objects | |
* | |
* @access private | |
* @params $DB::result() | |
* @returns stdClass | |
*/ | |
protected function _objectify($result) { | |
$this->_result = $result; | |
foreach ($this->relationships['has_one'] as $has_one) { | |
$this->_has_one($has_one); | |
} | |
return $this->_result; | |
} | |
/* _has_one() | |
* Reformats the result object for has_one relationships | |
* | |
* @access private | |
* @params string | |
* @returns void | |
*/ | |
private function _has_one($child) { | |
if (is_array($this->_result)) { | |
foreach ($this->_result as $key => $result) { | |
$fk = $child . '_id'; | |
if (isset($result->$fk)) { | |
$result->$child = new stdClass(); | |
foreach ($result as $key => $val) { | |
if (substr($key, 0, strlen($child) + 1) == $child . '_') { | |
$new_key = substr($key, (strlen($child) + 1) - strlen($key)); | |
$result->$child->$new_key = $val; | |
unset($result->$key); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment