Using PHP with Private Composer Libraries
If you want to have a private PHP library in your project and that isn’t publicly available via composer, you can still load the library via PSR-4 by modifying your composer.json
file. It is pretty easy to do, but even easier with our basic example. Following this example you will be using your own private libraries in no time!
The first step is to create a folder where a library or module will be located. It can be called whatever you want; lib
, libraries
, Libs
, src
are some common examples. The folder can be in your project's root or in a subfolder like app
.
Inside your new folder create a folder called TestLibraryFolder
with a file called TestLibraryClass.php
inside it. When naming the subfolder the same as your namespace it makes things confusing, so best avoid doing this.
The next step will be changing the composer.json
, put a new library namespace and path to the section autoload
->psr-4
in the composer.json
.
For our TestLibraryFolder
library in the app/Libs/
folder the changes will be:
"autoload": {
"psr-4": {
"App\\": "app/",
...
"TestLibrary\\": "app/Libs/TestLibraryFolder"
}
}
Or if it’s in the lib/
folder:
"autoload": {
"psr-4": {
"App\\": "app/",
...
"TestLibrary\\": "lib/TestLibraryFolder"
}
}
And run the command composer dump
to update the list of autoloading classes.
After that it’s possible to get access to our library in the code:
<?phpnamespace App\Http\Contollers;use TestLibrary\TestLibraryClass;class SomeController extends Controller
{
public function index()
{
$library = new TestLibraryClass();
// ...
}
}
As you can see the composer provides a well-organized autoload tool which is easily configurable. It can be easy to forget when accessing your private library files via the use
language construct that it is use <namespace_root>/path_to_class
NOT use <folder_name>/path_to_class
.
We hope that these examples gives you enough to get started making private libraries for your project. Additionally we hope to have cleared up some common confusion that happens when using composer and autoloading classes via PSR-4.