3

I am trying to recreate Laravel ORM (Eloquent).

In Laravel we can do something like:

Model::where("condition1")->where("condition2")->get();

So far my attempts to recreate this lead me to write this code:

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 {}

But it wont work because both where functions have the same name...

How does the Laravel do it?

1
  • 1
    @yivi thanx for the answer , im reading about magic functions and trying some codes Commented Aug 11, 2019 at 11:02

1 Answer 1

3

I haven't seen how Eloquent does it, but way to achieve this would be not to declare the method you want to reuse in neither the base class, nor the extended class; and instead use the magic methods __call($method, $arguments) and __callStatic($method, $arguments).

A simple example would be this:

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 {

}

Which would be used as:

Child::foo()->foo();

The first foo() goes through __callStatic() in the Base class, because it's a static call. The second foo() goes through __call(), since it's a non-static call.

This would output:

static fooing
instance fooing

You can see it working here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.