phpnamespacescomposer-phpautoloadpsr-4

Can we add subdirectory manually after the psr-4 composer namespace path?


I have different versions of files which are stored in separate subfolders inside a main folder. I intend to use subfolder based on a dynamically determined value of $ver.
Can I create a psr-4 composer namespace for the main folder and then add to it the $ver for subfolders as needed.
I tried following but its showing errors.

File Structure:

web\  
  public\index.php 
  main\
        V1\app.php
        V2\app.php
        V3\app.php

Composer:

    "autoload": {
        "psr-4": {
            "Application\\": "main"
        }
    }

index.php:

use Application;

$ver = "V2"; // suppose its V2 for now

$app = new "\Application\" . $ver . "\App()";

app.php:

namespace Application;  
class App {

}


Solution

  • You must follow PSR-4 for class naming and app structure:

    composer.json
        "autoload": {
            "psr-4": {
                "Application\\": "main"
            }
        }
    main/V1/App.php
        namespace Application\V1;
        class App {}
    

    For instance class with dynamic name use next construction:

    $ver = "V2"; // suppose its V2 for now
    $appClass = "\Application\$ver\App";
    $app = new $appClass;
    

    Read more about this here

    And i recommend to use factory pattern for this case:

    class App implements AppInterface {}
    class AppFactory
    {
        public static function makeApp(string $version): AppInterface
        {
             $appClass = "\Application\$version\App";
             if(! class_exists($appClass){
                 throw new Exception("App version $version not exists");
             }
             return new $appClass;
        }
    }