Joomla JDatabase:奇怪地使用 class 属性或方法的 selectRowNumber

Joomla JDatabase: selectRowNumber strange use of class attribute or method

在 Joomla 3.9.16 中有一个策略使用 class 属性,它也被用作方法!

在libraries/joomla/database/query.php中可以找到:

protected $selectRowNumber = null;

还有

public function selectRowNumber($orderBy, $orderColumnAlias)
{
  $this->validateRowNumber($orderBy, $orderColumnAlias);
  $this->select("ROW_NUMBER() OVER (ORDER BY $orderBy) AS $orderColumnAlias");

  return $this;
}

看了这个方法你就明白为什么一样了class:

protected function validateRowNumber($orderBy, $orderColumnAlias)
{
  if ($this->selectRowNumber)
  {
    throw new RuntimeException("Method 'selectRowNumber' can be called only once per instance.");
  }

  $this->type = 'select';

  $this->selectRowNumber = array(
    'orderBy' => $orderBy,
    'orderColumnAlias' => $orderColumnAlias,
  );
}

当你第一次调用$this->selectRowNumber()作为方法时,它调用$this->validateRowNumber(),其中$this->selectRowNumber()变成了一个数组! 如果你再次调用 $this->selectRowNumber() 它会抛出一个异常,因为你只能调用它一次并且不再是一个方法。

我想知道这是否是一个好的编程习惯,我认为绝对不是,因为它不容易理解和维护。也许你可以用另一种更清晰和线性的方式获得相同的结果。 我想问的是:我是对的还是这是一种普遍做法?

谢谢

你是说你可以重现这个错误?我假设您误读了脚本。

在我看来,第一次调用了 selectRowNumber() 方法,然后在 validateRowNumber() 中检查了 class variable/property $this->selectRowNumber真实性。

由于是null(falsey)第一次,所以没有抛出异常。

classvariable/property(不是方法)更新为

$this->selectRowNumber = array(
    'orderBy' => $orderBy,
    'orderColumnAlias' => $orderColumnAlias,
  );

然后回到里面selectRowNumber()ROW_NUMBER() OVER (ORDER BY $orderBy) AS $orderColumnAlias 字符串应用于 $this->select().

因为 ROW_NUMBER() OVER (ORDER BY $orderBy) AS $orderColumnAlias 不能对给定的查询应用两次,安全措施/抛出的异常检查是否为真 class variable/property —— 当然是因为它有已从 null 修改为非空关联数组。

属性和方法同名会不会令人困惑?当然。两者之间的唯一区别是尾随 ().

这是可以接受的编码做法吗?好吧,就可读性而言,它并不理想。但是,一旦一个项目标准化了它的命名约定,有时就会出现这种趋同的名称。代码库越大,发生这种情况的可能性就越大。我认为在这种孤立的情况下,一致性比可读性更重要。