Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I was digging into the source of a Composer package on github I noticed that there were php files that matched namespace names but were preceded with an underscore. Puzzled I pulled the package down (via Composer) and noticed that the class loader that Composer generates required these underscored files explicitly, not autoloading as I'd expected.

For instance, in the crunch/regular-expression package there is a namespace called CrunchRegularExpression:

-- src
---- Crunch
------- RegularExpression       <-- folder containing classes
------- _RegularExpression.php  <-- file namespace to Crunch/RegularExpression
                                    containing functions and constants 
                                    (instead of a class)

Initially I thought these underscored files were a feature of PSR-0 that I had missed, but then I looked at the Composer generated autoload_real.php and saw that _RegularExpression.php (amongst others) was being required explicitly:

…
$loader->register(true);

require $baseDir . '/src/Crunch/_RegularExpression.php';
require $baseDir . '/src/Crunch/RegularExpression/_Modifier.php';
require $baseDir . '/src/Crunch/RegularExpression/Pattern/_Modifier.php';
require $baseDir . '/src/Crunch/RegularExpression/Pattern/_Assertion.php';

return $loader;
…

Haven't been able to find any meaningful documentation about this feature of Composer. Is it a good "standard" for exporting non-class based namespaced dependencies, like functions and constants?

Update

My question turned out to be a slight misnomer. The selected answer lead me to discover that non-class based assets can be explicitly declared for loading in composer.json:

"autoload": {
    "psr-0": { "Crunch\RegularExpression": "src" },
    "files": [
        "src/Crunch/_RegularExpression.php",
        "src/Crunch/RegularExpression/_Modifier.php",
        "src/Crunch/RegularExpression/Pattern/_Modifier.php",
        "src/Crunch/RegularExpression/Pattern/_Assertion.php"
    ]
}

The underscores on the files were a convention used to delineate them from class definitions and have no special purposes in autoloading.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
493 views
Welcome To Ask or Share your Answers For Others

1 Answer

Composer doesn't treat those files in any special way. The package author in this case used this as some sort of convention to stores functions it seems.

The files are required by Composer because they're defined as "files" autoload in the composer.json, not because of some black magic on filenames.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...