我正在尝试重新创建Laravel ORM(Eloquent)。
在Laravel中,我们可以执行以下操作:
Model::where("condition1")->where("condition2")->get();
到目前为止,我试图重新创建此代码的尝试使我编写了以下代码:
class DB {
static $condition ;
public static function chidlClassName() {
return get_called_class();
}
static function where( $cond ) {
self::$condition[] = $cond;
return new DB();
}
public function where( $cond ){
self::$condition[] = $cond ;
return $this;
}
function get(){
$cond = implode(' AND ' ,self::$condition);
}
}
class Modle extends DB {}
但是它不会起作用,因为两个where
函数具有相同的名称...
Laravel如何做到?
答案 0 :(得分:1)
我还没有看到Eloquent如何做到这一点,但是实现这一目标的方法将不在基类和扩展类中都声明要重用的方法。而是使用the magic methods __call($method, $arguments)
和__callStatic($method, $arguments)
。
一个简单的例子是这样:
class Base {
public static function __callStatic($method, $arguments) {
if ('foo' === $method) {
echo "static fooing\n";
}
return new static();
}
public function __call($method, $arguments) {
if ('foo' === $method) {
echo "instance fooing\n";
}
}
}
class Child extends Base {
}
将用作:
Child::foo()->foo();
第一个foo()
通过__callStatic()
类中的Base
,因为它是静态调用。第二个foo()
通过__call()
,因为它是非静态调用。
这将输出:
static fooing
instance fooing
您可以看到它在here下工作。