简体   繁体   English

在PHP中链接方法时,是否可以确定首先调用哪个方法?

[英]When chaining methods in PHP, Is it possible to determine which method was called first?

So I am writing a PHP class at the moment to help make construction of SQL statements easier. 因此,我现在正在编写一个PHP类,以帮助简化SQL语句的构造。 I am writing them so that each method returns an instance of the object ( return $this ) in order to enable method chaining. 我正在编写它们,以便每个方法都返回对象的实例( return $this )以便启用方法链接。

Is it possible to test whether a method being called is a part of a method chain and which methods have been executed already in the method chain? 是否可以测试被调用的方法是否是方法链的一部分,以及方法链中已经执行了哪些方法? For example, in the below code, I would like the 'from' method to test whether it was called as part of a chain with the select() method directly before it. 例如,在下面的代码中,我希望使用“ from”方法来测试它是否直接在其前面的select()方法中作为链的一部分被调用。

$object->select('john', 'chris')->from('people');

Thanks in advance! 提前致谢!

I think it is not necessary to check sequence of called methods. 我认为没有必要检查调用方法的顺序。 You can create one finally method (for example execute() ), and in it check all attributes you needed for query, if any attribute is missing (for example select ) you can set default value for it: if available(for example 'select' => '*' ). 您可以创建一个finally方法(例如execute() ),并在其中检查查询所需的所有属性,如果缺少任何属性(例如select ),则可以为其设置默认值:如果可用(例如'select' => '*' )。

But in any case if you want to check is some method called before concrete method, you can set private attribute to keep methods requirements. 但是无论如何,如果要检查的是在具体方法之前调用的某种方法,则可以设置private属性来满足方法要求。 For example: 例如:

private $_methodsRequirements = array(
    'from' => array('select'),
    'set' => array('update', 'where'),
    // and all requiriments for each method
)
private $_calledMethods = array();

and create additional method for checking methods "callability": 并创建用于检查方法“可调用性”的其他方法:

private function checkCallability($method) {
    $requiredMethods = $this->_methodsRequirements[$method];
    foreach($requiredMethods as $m) {
        if(!in_array($m, $this->_calledMethods)) {
            throw new Exception('You must call method "'.$m.'" before calling method "'.$method.'"!');
        }
    }
    return true;

}

and on begin of each method you must call it: 在每种方法开始时,您必须调用它:

public function select() {
   $this->checkCallability(__METHOD__);
   // your query generation
   array_push($this->_calledMethods, __METHOD__);
}

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

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