Rick Brunken
Rick Brunken

Reputation: 130

Autoloading PHP file in composer package

I'm trying to create a composer package that also contains src/functions.php with some general functions. I have the following in composer.json to make it autoload:

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

When I import this package into a project it will try to load src/functions.php in the current project (local) in stead of the imported package. Is there a way to ensure the correct file is loaded when imported (./vendor/bla/src/functions.php)?

Upvotes: 2

Views: 602

Answers (1)

Marcin Orlowski
Marcin Orlowski

Reputation: 75619

Autoloading is not for loading everything. If src/functions.php contains class just ensure it's properly namespaced and I see no reason why autoloader would pick your local class instead of package's. If you are using the same namespace for the package and for code in your project then basically you should stop doing so.

If src/functions.php is just bunch of functions, then I strognly suggest refactoring the code and wrap them in properly namespaced class. You can make your functions static methods so basically not much would change from usage perspective.

EDIT

Once you finish refactoring, change your composer.json from what you shown in question to:

"autoload": {
    "classmap": ["src/"]
}

Upvotes: 2

Related Questions