23

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?

Letharion
  • 4,067
  • 7
  • 31
  • 42

1 Answers1

49

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.

Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • 2
    Any chance you could post update the answer with simple code examples with a dummy class or two? Despite reading the documentation you linked to, and comparing my directory/namespacing with those used in vendor/, I can't get my classes to load. – Letharion Sep 04 '12 at 17:43