2010-03-29 3 views
1

일부 동적 메서드를 사용하여 ActiveRecord 클래스를 확장하려고합니다. 내 컨트롤러에서 이것을 실행할 수 있습니다.PHP로 동적 메서드를 만드는 방법은 무엇입니까?

$user = User::find_by_username(param); 
$user = User::find_by_email(param); 

나는 과부하에 대해 조금 읽었으며 그 것이 중요하다고 생각했습니다. 나는 AR 클래스에서 static $_attributes을 얻었고,이 경우에 내 모델 (User = users)을 복수형으로 사용하여 테이블 이름을 얻는다.

어떻게하면됩니까? 모든 모델은 ActiveRecord 클래스를 확장합니다.

답변

2

당신이 또한 유용 할 수 PHP5.3

public static function __callStatic($name, $arguments) { 
/* 
    Use strpos to see if $name begins with 'find_by' 
    If so, use strstr to get everything after 'find_by_' 
    call_user_func_array to regular find method with found part and $arguments 
    return result 
*/ 
} 
+0

PHP 5.3 정말 좋은 기능을 가지고 :) – sandelius

0

, 더 복잡으로 사용할 수있는 __callStatic() magic method를 사용해야하지만, 멤버 변수에 액세스 할 수있는 진정한 동적 기능을 할 수 있습니다.

class DynamicFunction { 
    var $functionPointer; 
    var $mv = "The Member Variable"; 

    function __construct() { 
     $this->functionPointer = function($arg) { 
      return sprintf("I am the default closure, argument is %s\n", $arg); 
     }; 
    } 

    function changeFunction($functionSource) { 
     $functionSource = str_replace('$this', '$_this', $functionSource); 
     $_this = clone $this; 

     $f = '$this->functionPointer = function($arg) use ($_this) {' . PHP_EOL; 
     $f.= $functionSource . PHP_EOL . "};"; 
     eval($f); 
    } 

    function __call($method, $args) { 
     if ($this->{$method} instanceof Closure) { 
      return call_user_func_array($this->{$method},$args); 
     } else { 
      throw new Exception("Invalid Function"); 
     } 
    } 
} 

if (!empty($argc) && !strcmp(basename($argv[0]), basename(__FILE__))) { 
    $dfstring1 = 'return sprintf("I am dynamic function 1, argument is %s, member variables is %s\n", $arg, $this->mv);'; 
    $dfstring2 = 'return sprintf("I am dynamic function 2, argument is %s, member variables is %s\n", $arg, $this->mv);'; 

    $df = new DynamicFunction(); 
    $df->changeFunction($dfstring1); 
    echo $df->functionPointer("Rabbit"); 

    $df->changeFunction($dfstring2); 
    $df->mv = "A different var"; 
    echo $df->functionPointer("Cow"); 
}; 
관련 문제