2

I am trying to load my class through namespacing but Im struggling to find the right configuration and I keep getting a class not found error.

Here is the psr-4 property in my composer.json

"psr-4": {
    "Namespaceone\\": [
        "src/core/Modules/Moduleone",
        "src/core/Modules/Moduletwo",
    ],
    "Volvo\\": [
        "src/programme/volvo/",
        "src/programme/volvo/volvoxc"
    ]
}

Here is the file structure of src/programme/volvo:

- init.php  //Contains new Volvo()
- Volvo.php //Class Volvo
- volvoxc/
  - Volvoxc.php //Class Volvoxc extends Volvo

The files and classes:

init.php

$volvo = new Volvo(); //This returns all the properties from Volvo()

Volvo.php

namespace Volvo;
use Volvoxc;
class Volvo {
  $volvoxc = new Volvoxc();
}

Volvoxc.php //This class can not be found

namespace Volvo;
class Volvoxc extends Volvo {}
3
  • 2
    Class Volvoxc needs the namespace Volvo\Volvoxc. But make the directory uppercase Volvoxc instead of volvoxc and remove "src/programme/volvo/volvoxc" from the second definition. Commented May 16 at 7:56
  • Related documentation composer. Commented May 16 at 8:09
  • Resp: PSR-4. Commented May 16 at 8:14

1 Answer 1

2

The PSR-4 notation in your composer.json file looks slightly complicated on the first view. It would be easier with single entries for every namespace to use.

As @Álvaro-gonzáles stated out in the comments, it is allowed to provide a list of directories for one same prefix, as stated out in the composer docs. Although it is possible this example relies on single entries in the composer PSR-4 config.

"psr-4": {
    "NamespaceOne\\ModuleOne\\": "src/core/Modules/ModuleOne/",
    "NamespaceOne\\ModuleTwo\\": "src/core/Modules/ModuleTwo/",
    "Volvo\\": "src/programme/Volvo/"
}

You define these three sources and therefore you can slightly adjust your namespaces.

<?php

// src: src/programme/Volvo/VolvoXC/Volvo.php

declare(strict_types=1);

namespace Volvo\VolvoXC;

use Volvo\Volvo as BaseVolvo;

final class Volvo extends BaseVolvo
{
}

The Volvo namespace is defined once and everything in this namespace and its subfolders will be found automatically through PSR-4 autoloading.

Sign up to request clarification or add additional context in comments.

1 Comment

You're in fact allowed to provide a list of directories for one same prefix: getcomposer.org/doc/04-schema.md#psr-4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.