【问题标题】:PHP How to autoload the global namespace alias defined in the class filePHP如何自动加载类文件中定义的全局命名空间别名
【发布时间】:2015-09-12 10:17:49
【问题描述】:

在某些命名空间中,定义了一个具有静态方法的类。为了使名称更短,我为此方法使用速记别名。别名在全局命名空间中定义。 自动加载出现问题。在加载类之前不能使用别名。

示例。 假设如下结构

composer.json
index.php
src/
   Utils/
      Dumper.php

文件src/Utils/Dumper.php 定义类MyVendor\Utils\Dumper 并在全局命名空间中定义别名_d()

<?php
namespace MyVendor\Utils {
  class Dumper 
  {
    public static function show($x) 
    {
       echo "<pre>" . print_r($x, true) . "</pre>";
    }
  }
}

namespace {
  if ( !function_exists( '_d' ) ) {
    function _d() 
    {
      $_ = func_get_args();
      return call_user_func_array( 
        array( 'MyVendor\Utils\Dumper', 'show' ),
        $_
      );
    }
  }
}
?>

文件 composer.json 创建 PSR-4 自动加载器。

{
    "autoload": {
        "psr-4": {
            "MyVendor\\": "src/"
        }
    }
}

我不能使用别名_d(),因为不需要类Dumper。 代码

<!DOCTYPE html>
<html lang="en">
<head> <meta charset='utf-8'> </head>
<body>
<?php 
require_once 'vendor/autoload.php';

use MyVendor\Utils\Dumper;

$arr = array(10, 20, 30);

//Dumper::show($arr);
_d($arr);
?>
</body>
</html> 

导致Fatal error: Call to undefined function _d() in index.php on line 13

有一个明显的解决方案。一旦使用了Dumper,它就必须被自动加载,所以整个src/Utils/Dumper.php 都被包含在内,并且还生成了别名。

Dumper::show($arr);
_d($arr);

但这不是我的意思。 每当我将我的Utils 包移动到另一个项目时,我都必须记住第一次使用Dumper::show()。 任何其他用户也必须意识到这个障碍。

有没有更好的解决方案?

【问题讨论】:

    标签: php namespaces


    【解决方案1】:

    我会使用类似 composer 'files' 功能的东西,然后将速记 _d() 函数移到包根目录中的 bootstrap.php 中。

    示例用法:

    {
        "autoload": {
            "files": ["src/MyLibrary/functions.php"]
        }
    }
    

    https://getcomposer.org/doc/04-schema.md#files

    【讨论】:

      猜你喜欢
      • 2013-02-07
      • 2013-11-22
      • 2013-11-25
      • 2014-04-13
      • 2011-04-08
      • 2011-01-15
      相关资源
      最近更新 更多