如何自动加载类文件中定义的全局命名空间别名


PHP How to autoload the global namespace alias defined in the class file

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

的例子。假设如下结构

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()。其他用户也必须意识到这个障碍。

有更好的解决方案吗?

我会使用类似于composer 'files'功能的东西,并将缩略的_d()函数移出到包根目录中的bootstrap.php

使用例子:

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

看到https://getcomposer.org/doc/04-schema.md文件