PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

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

 February 05, 2022     autoload, composer-php, namespaces, php, psr-4     No comments   

Issue

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;
    }
}


Answered By - Maksim
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing