3.1. Basics - shinokada/php_notes GitHub Wiki

Basic usage

composer install vs composer update

The composer install command checks if a lock file is present, and if it is, it downloads the versions specified therei (regardless of what composer.json says). If no composer.lock file exists, Composer will read the dependencies and versions from composer.json and create the lock file after executing the update or the install command.

This means that if any of the dependencies get a new version, you won't get the updates automatically. To update to the new version, use the update command. This will fetch the latest matching versions (according to your composer.json file) and also update the lock file with the new version.

Autoloading

Create a composer.json with only curly bracket.

{

}

Then composer install. This will create a autoload.php.

You can even add your own code to the autoloader by adding an autoload field to composer.json.

{
    "autoload": {
        "psr-4": {"Acme\\": "src/"}
    }
}

Composer will register a PSR-4 autoloader for the Acme namespace.

You define a mapping from namespaces to directories. The src directory would be in your project root, on the same level as vendor directory is. An example filename would be src/Foo.php containing an Acme\Foo class.

Add namespace Acme; to all the files under src. After adding the autoload field, you have to re-run composer dump-autoload to re-generate the vendor/autoload.php file.

Including that file will also return the autoloader instance, so you can store the return value of the include call in a variable and add more namespaces. This can be useful for autoloading classes in a test suite, for example.

$loader = require 'vendor/autoload.php';
$loader->add('Acme\\Test\\', __DIR__);

In addition to PSR-4 autoloading, classmap is also supported. This allows classes to be autoloaded even if they do not conform to PSR-4. See the autoload reference for more details.

To use it, use Namespace\classname.

$testone = new Acme\Person('John Doe');

Or use Acme\Person

use Acme\Person
$testone = new Person('John Doe');
⚠️ **GitHub.com Fallback** ⚠️