mwloda
mwloda

Reputation: 491

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

In some namespace there is defined a class with the static method. To make names shorter I use shorthand alias for this method. The alias is defined in the global namespaces. There occurs problem with autoloading. The alias cannot be used until the class is loaded.

Example. Assume following structure

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

File src/Utils/Dumper.php defines class MyVendor\Utils\Dumper and also defines alias _d() in the global namespace

<?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' ),
        $_
      );
    }
  }
}
?>

File composer.json creates PSR-4 autoloader.

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

I cannot use the alias _d() since there is no requirement for class Dumper. The code

<!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> 

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

There is an obvious solution. Once the Dumper is used, it has to be autoloaded, so entire src/Utils/Dumper.php is included and also alias is made.

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

But that is not my point. Anytime I move my Utils package to another projects I would have to remember to use Dumper::show() for the first time. Any other user must also be aware of this obstacle.

Is there any better solution?

Upvotes: 1

Views: 2311

Answers (1)

Christoffer Bubach
Christoffer Bubach

Reputation: 1686

I'd go with something like the composer 'files' functionality, and move out that shorthand _d() function to for example a bootstrap.php in the package root.

Example usage:

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

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

Upvotes: 1

Related Questions