0

Suppose if you wanted to call few methods from another object. What is the proper way of doing it.

And if you use __call(), is it possible to extract the arguments, instead of using it as array.

Example:

<?php

class Component
{
    protected $borrowMethods = array();

    public function __call( $name, $args )
    {
        if( isset( $this->borrowMethods[$name] ) )
        {
            $obj = $this->borrowMethods[$name] ;
            return $obj->$name( $this->argExtractFunc($args) );
        }

        throw new \Exception( 'method not exists' );
    }
}

class ActiveRecord extends Component
{
    protected $validator; //instance of validator 

    protected $borrowMethods = array(

        'validate' => 'validator',
        'getError' => 'validator',
        'moreMethods' => 'someOtherClass',
    );

    public function save()
    {
        if($this->validate())
        {

        }
    }
}

class Validator
{

    public function validate(){}

    public function getError( $field ){}

}

$ar = new ActiveRecord;

$ar->getError( $field );
yprez
  • 14,854
  • 11
  • 55
  • 70
eskylite
  • 1
  • 1

2 Answers2

1

Not sure I completely undestand what you're asking, but I believe what you're referring to is known as Method chaining. Each of your methods needs to return $this (or another object), which the original caller can then immediately call another method on.

class Test
{
    public function one() {
        echo 'one';
        return $this;
    }

    public function two() {
        echo 'two';
        return $this;
    }

}

$test = new Test();
$test->one()->two();  // <-- This is what I think you're trying to do

Update

In regards to your update, I don't think that is good design practice. How much maintenance would the $borrowMethods array require? How much more tightly bound is your ActiveRecord implementation to your Validator? Instead, why not just implement your own getError method within ActiveRecord that returns the results of calling $validator->getError($field) ?

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
0

What you're looking for is called method chaining. See this SO topic: PHP method chaining?

The arguments in __call() can be obtained through: func_get_args()

Community
  • 1
  • 1
Gerben Jacobs
  • 4,515
  • 3
  • 34
  • 56