Custom code management with the Composer auto loader?

后端 未结 1 751
一生所求
一生所求 2020-12-24 02:41

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

相关标签:
1条回答
  • 2020-12-24 03:03

    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.

    0 讨论(0)
提交回复
热议问题