3

我有一组用于数据存储的类。它目前有一个用于 Google Drive、Dropbox、Box、FTP 和本地连接的工作连接器。我设计它是为了构建一个文件管理器,客户端可以在其中管理多个数据存储源。

我的问题来了。目前,我对该addConnection()方法的实现如下:

// addConnection - adds a storage connection to the storage manager
public function addConnection($service, $credentials) {
    if (!empty($service) && !empty($credentials)) {
        if (in_array($service, [Connectors\Box, Connectors\Dropbox, Connectors\FTP, Connectors\GoogleDrive, Connectors\Local], true)) {
            // rest goes here...
        }
    }
}

我将常量放在一个单独的命名空间中,如下所示:

namespace Services\Storage\Connectors {
    const Box = "Box";
    const Dropbox = "Dropbox";
    const FTP = "FTP";
    const GoogleDrive = "GoogleDrive";
    const Local = "Local";
}

有没有办法让我为给定的命名空间获取所有定义的常量?这样,我可以构造一个函数来获取所有定义的常量并编写更优雅的东西,例如in_array($service, getConstants($this->getNamespace()), true).

你能给我一个提示吗?

4

1 回答 1

3

您可以使用以下命令获取所有用户定义的常量,get_defined_constants然后使用以下命令检查命名空间strpos

$constants = get_defined_constants(TRUE)['user'];

foreach ($constants as $name => $value)
{

  if (0 === strpos($name, 'services\storage\connectors'))
  {
    $services_storage_connectors[] = $name;
  }

}

echo '<pre>' . print_r($services_storage_connectors, TRUE) . '</pre>';

/*

Array
(
    [0] => services\storage\connectors\Box
    [1] => services\storage\connectors\Dropbox
    [2] => services\storage\connectors\FTP
    [3] => services\storage\connectors\GoogleDrive
    [4] => services\storage\connectors\Local
)

*/

Note that $name is lowercase, even if the namespace is defined with uppercase letters.

Edit: In case you'd like it in fewer lines

  $constants = array_filter(array_keys(get_defined_constants(TRUE)['user']), function ($name)
  {
    return 0 === strpos($name, 'services\storage\connectors');
  }
  );
于 2013-03-29T22:45:28.417 回答