michaelward82
michaelward82

Reputation: 4736

PHP: Call parent magic method from function of same name

I am using an ORM class - each table in the DB is represented using a subclass of the ORM class.

I am using PHP interfaces, and I wish to specify which methods (db fields) are required in some of my ORM subclasses. Adding a function to an interface requires the method to be explicitly declared in the class. However, these methods rely on magic methods for the actual functionality as the DB structure is unknown to the ORM before run time.

What I imagined doing was creating functions for each, which would return a result from the parent class.

Consider:

class ORM
{
    // Library code here. Can't change this.

    public function __call($name, $arguments)
    {
        return call_user_func_array(array($this, $method), $arguments);
    }
}

interface MyTableInterface
{
    public function myDbField();
}

class MyTable extends ORM implements MyTableInterface
{
    public function myDbField()
    {
        return parent::myDbField();
    }
}

With this code, when I call parent::myDbField() from the MyTable class, it correctly moves to the ORM class and uses the __call magic method. Once here, $this equals MyTable and it calls the original function from the MyTable class instead of initiating it's own logic to pull info from the DB.

How can I avoid this recursion?

Upvotes: 0

Views: 226

Answers (2)

ilpaijin
ilpaijin

Reputation: 3695

One way to do it could be passing $orm instance as a dep (constructor, setter or whatever logic). Ex:

class MyTable {
    protected $orm;
    public function __construct(Orm $orm)
    {
        $this->orm = $orm;
    }
    public function myDbField()
    {
        return $this->orm->myDbField();
    }
}

This way, $this inside Orm __call refers to Orm instance. Perhaps, this could be a scenario to use adapter pattern?

Upvotes: 1

Jérémy Dutheil
Jérémy Dutheil

Reputation: 6137

call method is only invoked when there is no method found, in your example it is not possible because the method is found in the subclass

Upvotes: 0

Related Questions