From 5d295ea39a88aa77122280d15defb5da589fc166 Mon Sep 17 00:00:00 2001 From: Everton Leite Date: Wed, 17 Sep 2014 09:48:08 -0300 Subject: [PATCH] Created functions to make possible to create static methods on models, using a static variable that is an instance of the current class and can be used to access the codeigniter methods based on objects. Would be like: static function find($id){ self::getInstance()->db->where("id", $id); $result = self::getInstance()->db->get("user")->result(); return count($result) == 1 ? $result[0] : null; } And can be called by $user = User::find(10); --- core/MY_Model.php | 58 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/core/MY_Model.php b/core/MY_Model.php index 05add98..9c94ebe 100644 --- a/core/MY_Model.php +++ b/core/MY_Model.php @@ -937,4 +937,60 @@ protected function _return_type($multi = FALSE) $method = ($multi) ? 'result' : 'row'; return $this->_temporary_return_type == 'array' ? $method . '_array' : $method; } -} + + /** + * Return the class name of the current call + * @param boolean $bt + * @param integer $l + * @return type + */ + static function get_called_class($bt = false, $l = 1) { + if (!$bt) $bt = debug_backtrace(); + if (!isset($bt[$l])) throw new Exception("Cannot find called class -> stack level too deep."); + if (!isset($bt[$l]['type'])) + throw new Exception ('type not set'); + else switch ($bt[$l]['type']){ + case '::': + $lines = file($bt[$l]['file']); + $i = 0; + $callerLine = ''; + do{ + $i++; + $callerLine = $lines[$bt[$l]['line']-$i] . $callerLine; + } while (stripos($callerLine,$bt[$l]['function']) === false); + preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/', $callerLine, $matches); + if (!isset($matches[1])) + throw new Exception ("Could not find caller class: originating method call is obscured."); + switch ($matches[1]){ + case 'self': + case 'parent': + return self::get_called_class($bt,$l+1); + default: + return $matches[1]; + } + case '->': switch ($bt[$l]['function']){ + case '__get': + if (!is_object($bt[$l]['object'])) throw new Exception ("Edge case fail. __get called on non object."); + return get_class($bt[$l]['object']); + default: return $bt[$l]['class']; + } + default: throw new Exception ("Unknown backtrace method type"); + } + } + + /** + * This will keep a instance of the current class to be used on static methods, like singleton + * @var Current_class + */ + private static $_instance; + + /** + * Return a instance of the current class to be used on static methods + * @return class_instance + */ + static function getInstance(){ + if (self::$_instance == null) + eval("self::\$_instance = new ".(self::get_called_class())."();"); + return self::$_instance; + } +} \ No newline at end of file