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

时间:2015-09-12 10:17:50

标签: php namespaces

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

实施例。 假设以下结构

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

有没有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

我会选择类似作曲家的文件&#39;功能,并将该简写_d()函数移出到包根中的bootstrap.php

使用示例:

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

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