Skip to content
Advertisement

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  
  publicindex.php 
  main
        V1app.php
        V2app.php
        V3app.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 {

}

Advertisement

Answer

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

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

For instance class with dynamic name use next construction:

$ver = "V2"; // suppose its V2 for now
$appClass = "Application$verApp";
$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$versionApp";
         if(! class_exists($appClass){
             throw new Exception("App version $version not exists");
         }
         return new $appClass;
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement