简体   繁体   中英

Concept of code piping in PHP

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 );

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) ?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM