[英]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. 如果使用
__call()
,是否可以提取参数,而不是将其用作数组。
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. 您的每个方法都需要返回
$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
Update 更新
In regards to your update, I don't think that is good design practice. 关于您的更新,我认为这不是好的设计习惯。 How much maintenance would the
$borrowMethods
array require? $borrowMethods
数组需要多少维护? How much more tightly bound is your ActiveRecord
implementation to your Validator
? 您的
ActiveRecord
实现与Validator
绑定程度是多少? Instead, why not just implement your own getError
method within ActiveRecord
that returns the results of calling $validator->getError($field)
? 相反,为什么不只在
ActiveRecord
中实现自己的getError
方法,该方法返回调用$validator->getError($field)
?
What you're looking for is called method chaining . 您正在寻找的方法称为方法链接 。 See this SO topic: PHP method chaining?
看到这个主题: PHP方法链接?
The arguments in __call()
can be obtained through: func_get_args()
__call()
的参数可以通过以下方式获取: func_get_args()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.