1

Is it safe to assume that any composer based module package will have a PSR 4 autoloader section whose prefix is the full module name? i.e.

"autoload": {
    "psr-4": {
        "Foo\\Bar\\": "src/"
    }
}

or are people doing different, clever things with autoloaders in Magento 2? If so what are those different clever things?

2

No, that is not a safe assumption, at least from the module name to namespace prefix mapping point of view.

When packages are split up, the old namespace prefixes can be kept for backward compatibility. Magento recently approved a design document that states that will be used a lot:

https://github.com/magento/architecture/blob/master/design-documents/module-separation-naming.md

In that document, the accepted section „Module naming“, paragraph 2.iii states:

——

Preserve old namespaces. Classes in CatalogAdminUi, CatalogStorefrontUi, CatalogCron, etc will have Catalog namespace ✅.

Pros.
▪ No overhead from preserving keeping backwards compatibility.

Cons.
▪ We going to have namespaces that don't follow the pattern.
▪ Will need to fix existing tests (not a big con really).
▪ Will have to decide what to do with new classes we introduce in the modules that have classes with old namespaces. Introduce with old namespace for consistency or with new namespace that matches module name to have correct namespace. Either way this might be a little confusing, and different from the case when we create brand new module with correct namespace

——

Beyond that, I think the only thing safe to assume is that the autoload section contains a configuration that will have composer generate an autoloader that will allow using the contained classes. Some packages for example contain more than one Magento module.

  • Do you know of a M2 composer based module package that doesn't use it? I would be keen to take a look – Dominic Xigen Oct 2 at 12:20
  • 1
    @DominicXigen I remember I’ve seen modules ported from M1 that used psr-0 so they could load legacy library classes. I don’t remember the name though. I’ve seen some without psr-4 prefix configurations, relying on the global non-prefixed psr-4 declaration. Also, I’ve seen many other autoloader configurations in composer.json files, but not in M2 modules though. However I’m pretty sure they are out there, too. One thing I’ve cone to believe is that it’s never save a feature is not used. – Vinai Oct 2 at 13:04
1

Is it safe to assume that any composer based module package will have a PSR 4 autoloader section

Yes

or are people doing different, clever things with autoloaders in Magento 2

No

One of the most in depth articles I've read on autoloaders is something you wrote. I believe you know about as much as there is to know on the subject at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.