Cakephp的魔法函数解析,findBy…

Cakephp的一个非常有意思的特色,就是,可以通过它的Model使用类似于findBy(Fields)这样的方法直接取得数据的调用,例如,我们可以直接取得ID为5的数据,可以这样:

/**
在Controller中,我们可以这样写
*/
$data = $this->ModelName->findById(5);
pr($data);

就这么简单,但是,你会发现Model里面根本没有findById这个函数。:)

我翻遍了Cakephp的源代码,都没有找到相关的设置,呵呵。

yoophi老师说,它使用了overload,overload是php提供的非常有魅力的功能,它可以使类执行一些自己根本没有定义的功能。

在PHP5中,我们可以这样使用它

<?php
class OverLoadable{
	var $config;

	function __construct(){
		$this->config['val'] = array(
			'one' => '1',
			'two' => '2',
		);
	}

	function __call($method, $params){
		echo 'you called function name is: '.$method.'
'; echo 'you called the params is:'; echo '
';
		print_r($params);
		echo '

';
}

function __get($name){
return $this->config[$name];
}

function __set($name,$value){
$this->config[$name] = $value;
}
}

$oo = new OverLoadable();
$oo->testFunction('test',array(1,2,3));
$oo->theOthersSomeFunction('where','when','who','what');
$oo->val = 123;
echo $oo->val;
?>

overload包含三个魅力函数__call(),__get(),__set()分别是调用函数、获取属性、设置属性的回调函数,如果你在类中声明了这三个函数,那么,你对于这个类所有的函数调用、获取属性或者设置类属性,都会被相应的函数管理。

PHP4的代码稍稍有些不同,PHP4需要额外执行一个overload函数

例如:

<?
class Foo {
   // The properties array
   var $array = array('a' => 1, 'b' => 2, 'c' => 4);

   // Getter
   function __get($n, $val = "") {
       if (phpversion() >= 5) {
           return $this->array[$n];
       } else {
           $val = $this->array[$n];
           return true;
       }
   }

   // Setter
   function __set($n, $val) {
       $this->array[$n] = $val;
       if (phpversion() < 5) return true;
   }

   // Caller, applied when $function isn't defined
   function __call($function, $arguments) {
       // Constructor called in PHP version < 5
       if ($function != __CLASS__) {
           $this->$arguments[0] = $arguments[1];
       }
       if (phpversion() < 5) return true;
   }
}

// Call the overload() function when appropriate
if (function_exists("overload") && phpversion() < 5) {
   overload("Foo");
}

// Create the object instance
$foo = new Foo;

// Adjust the value of $foo->array['c'] through
// method overloading
$foo->set_array('c', 3);

// Adjust the value of $foo->array['c'] through
// property overloading
$foo->c = 3;

// Print the new correct value of $foo->array['c']
echo 'The value of $foo->array["c"] is: ', $foo->c;

?> 

 

而Cakephp本身,所有的Model都是继承自Overloadable的类,所以,它所有的Model都具有这个特性!

相关文章

什么是PHP的Overload?