繁体   English   中英

PHP中代码管道的概念

[英]Concept of code piping in PHP

假设您想从另一个对象中调用几个方法。 正确的做法是什么?

如果使用__call() ,是否可以提取参数,而不是将其用作数组。

例:

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

不确定我是否完全理解您的要求,但我相信您所指的就是方法链接 您的每个方法都需要返回$this (或另一个对象),然后原始调用者可以立即调用该方法。

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

更新

关于您的更新,我认为这不是好的设计习惯。 $borrowMethods数组需要多少维护? 您的ActiveRecord实现与Validator绑定程度是多少? 相反,为什么不只在ActiveRecord中实现自己的getError方法,该方法返回调用$validator->getError($field)

您正在寻找的方法称为方法链接 看到这个主题: PHP方法链接?

__call()的参数可以通过以下方式获取: func_get_args()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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