phpsymfonycomposer-phppsr-4

How to make Composer/PSR-4 make accepting my second namespace in a subfolder?


Given is a Symfony 4.4 Application (specifically, Sylius) using PSR-4 for autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "KYCBundle\\": "src/KYCBundle/"
        }
    },

Placing all Controllers and Entities and so on under the src directory works well so far:

+ src
  - Controllers
  - Entities

And the corresponding namespace is e.g.:

namespace App\Controller\Admin;

But for the second namespace KYCBundle this does not work.

+ src
   + KYCBundle
     - Controllers
     - Command
     - Entities

When I want to use Classes with the following namespace declaration:

namespace KYCBundle\Command\AccessTokenCommand

this will give an error:

Expected to find class "App\KYCBundle\Command\AccessTokenCommand" in file " ./src/KYCBundle/Command/AccessTokenCommand.php" while importing services from resource "../src/*", but it was not found! Check the namespace prefix used with the resource.

When I change the namespace from KYCBundle\Command into App\KYCBundle\Command thinks work well. Also, when I delete the second Line in PSR-4 configuration, things will not change which basically means that whether with or without the PSR-4 configuration for KYCBundle is not used at all.

How to let me use the namespace KYCBundle as the root level without the prefix App?


Solution

  • Do not put the classes from your second namespace within src. Avoid having nested namespaces "roots".

    Either put your second namespace outside src. E.g.:

    - ./src
    - ./KYCBundle
    

    Or have different roots within src:

    - ./src/App
    - ./src/KYCBundle
    

    Logically, modify your composer.json file to match your directory structure.