I have a list of utility functions for the classes I create inside a composer package. I can autoload the classes easily, but not sure how to setup the utility classes.
My file structure is:
composer.json
--src
--SomeClass.php
--utilities.php
In utilities.php
I have set up my namespace:
namespace PackageName\utilities {
function functionName() {}
function functionName2() {}
}
then when I load the utilities
file, I can use the functions like so:
use function PackageName\utilities\{functionName, functionName2};
functionName();
My issue is that everytime I want to use this utilities
file, I need to require it and it seems like a bad pattern. I want to use it with the main application that loads this package and also in the classes within the package.
I am more or less fine requiring it in with the class files like in SomeClass.php
:
namespace PackageName;
require_once 'utilities.php';
use PackageName\utilities\functionName;
class SomeClass {
function methodName() {
functionName();
}
}
Is it possible to autoload utilities
somehow with composer either with the parent project or within the composer.json
of the package?
EDIT: My current composer.json
file for the package looks like this:
{
"name": "packageauthor/packagename",
...
"autoload": {
"files: ["src/utilities.php"],
"psr-0": { "PackageName_": "src },
"psr-4": { "PackageName\\": "src" }
}
}
and the composer.json
of my parent project
{
"name": "packageauthor/project",
...
"require": {
"packageauthor/packagename": "1.0.0"
}
}
and in my parent project I have an index.php
that has
require_once 'vendor/autoload.php';
use PackageName\SomeClass;
use function PackageName\utilities\functionName;
new SomeClass(); // works
functionName(); // fatal error
I know I can make it work with adding this line to my project composer file:
"autoload": { "files: ["vendor/packageauthor/packagename/src/utilities.php"] }
but is there a way my package can use the file without requiring and my project without autoloading the file like that?