composer-phppsr-4psr-0

psr-0 autoloading with composer not wotking, but it works perfectly with psr-4 autoloading


I tried to autoload a file with PSR-0 ,but it is not auto loading that file. I tried the same file with PSR-4 auto loading. With PSR-4 it worked perfectly. Is there any difference in folder structure needed for PSR-0?

I couldn't make PSR-0 working even if keep the folder structure mentioned in What is the difference between PSR-0 and PSR-4?

Here is my folder structure.

Test
    --Package
        --Test.php

I have in Test.php:

<?php
namespace Test\Package;

class Test
{
    public function __construct()
    {
        echo "In Test class";
    }
}

and composer.json looks like

{
  "autoload": {

    "psr-0": {
            "Test\\Package\\": "Test/Package/"
             }
  }
}

Solution

  • Counter-intuitively, the composer documentation on PSR-0 includes a partial path making it seem that PSR-0 requires a path to the package in order to load classes. In reality, PSR-0 constructs the path based on the package, so it only needs a path specified if the code lives inside a folder like src/ or lib/ that is not part of the namespace path. If the namespace based directory structure starts in the same directory as composer.json, then no path is required.

    Assuming a directory structure as specified in the question, there's several ways to load this class using composer.

    PSR-0

    {
      "autoload": {
        "psr-0": { "Test\\Package\\": "" }
      }
    }
    

    Note that even though the code lives in Test/Package/, this folder is not specified in PSR-0.

    PSR-4

    For PSR-4 autoloading, the path to the package source must appear in the composer.json file.

    {
      "autoload": {
        "psr-4": { "Test\\Package\\": "Test/Package/" }
      }
    }
    

    Classmap

    When the requirement exists to load classes which aren't organized into the typical namespace folder tree, it is also possible to simply specify a list of folders in which to search for classes using the classmap array.

    {
      "autoload": {
        "classmap": [ "Test/Package/" ]
      }
    }
    

    In general, however, using PSR-0 or PSR-4 will provide an easier experience, as the classmap approach requires every folder to be separately specified.