I've started a new project, where I use Composer to handle some dependencies, as well as their auto-loading.
I only keep the composer.json file in the VCS, instead of the entire vendor directory, so I don't want to start adding my code in there.
How should I handle my own project specific code, so that it auto loads as well?
The simplest way is to autoload each class separately. For this purpose, all we need to do is define the array of paths to the classes that we want to autoload in the composer. json file.
Composer is an application-level dependency manager for PHP. Dependency simply means libraries/packages your application depends upon. Apart from managing the dependencies, composer will also autoload the files needed for the application.
Method 1: Enter a Command on the terminal This library will be saved in the vendor file in your PHP project. In addition, the vendor/autoload. php file is automatically created. This file is used for autoloading libraries for the PHP project.
This map is built by scanning for classes in all . php and . inc files in the given directories/files. You can use the classmap generation support to define autoloading for all libraries that do not follow PSR-0/4. To configure this you specify all directories or files to search for classes.
This is actually very simple. Excluding vendors directory from your repository is the right approach. Your code should be stored in a separate place (like src).
Use the autoload property to make that composer recognizes your namespace(s):
{ "autoload": { "psr-4": { "Acme\\": "src/" } } }
Assuming you have class names following the psr-4 standard, it should work. Below some example of class names and their locations on the file system:
Remember to define a namespace for each class. Here's an example of Acme\Command\HelloCommand:
<?php namespace Acme\Command; class HelloCommand { }
Don't forget to include the autoloader in your PHP controllers:
<?php require 'vendor/autoload.php';
Read more on PSR-4 standard on PHP Framework Interoperability Group.
Note that if you edit composer.json
, you need to either run install, update or dump-autoload to refresh the autoloader class paths.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With