Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom code management with the Composer auto loader?

Tags:

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?

like image 909
Letharion Avatar asked Sep 03 '12 11:09

Letharion


People also ask

How do I create a composer autoload?

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.

What is composer autoload files?

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.

How do you use autoload vendor?

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.

What is Classmap in composer json?

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.


1 Answers

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:

  • Acme\Command\HelloCommand -> src/Command/HelloCommand.php
  • Acme\Form\Type\EmployeeType -> src/Form/Type/EmployeeType.php

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.

like image 117
Jakub Zalas Avatar answered Oct 07 '22 15:10

Jakub Zalas