在 PHP 中链接方法时,是否可以确定首先调用哪个方法? [英] When chaining methods in PHP, Is it possible to determine which method was called first?

查看:50
本文介绍了在 PHP 中链接方法时,是否可以确定首先调用哪个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在正在编写一个 PHP 类来帮助简化 SQL 语句的构建.我正在编写它们,以便每个方法返回对象的一个​​实例 (return $this) 以启用方法链接.

So I am writing a PHP class at the moment to help make construction of SQL statements easier. I am writing them so that each method returns an instance of the object (return $this) in order to enable method chaining.

是否可以测试被调用的方法是否是方法链的一部分以及哪些方法已经在方法链中执行?例如,在下面的代码中,我希望 'from' 方法测试它是否作为链的一部分被调用,并在它之前直接使用 select() 方法.

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.

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

提前致谢!

推荐答案

我认为没有必要检查调用方法的顺序.您可以创建一个 finally 方法(例如 execute() ),并在其中检查查询所需的所有属性,如果缺少任何属性(例如 select),您可以为其设置默认值:如果可用(例如 'select' => '*').

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' => '*').

但无论如何,如果您想检查某个方法是否在具体方法之前调用,您可以设置 private 属性以保留方法要求.例如:

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. 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__);
}

这篇关于在 PHP 中链接方法时,是否可以确定首先调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆