Namespaces, Autoloading and Composer

Use Composer and PSR-4 in a plugin without a vendor/ conflict that breaks another plugin on the same site.

Two plugins, one library, two versions. The first one loaded wins. Your plugin ships Guzzle 7, another one ships Guzzle 6, and the site breaks in a place neither of you touched. This module covers namespaces, autoloading and the prefixing that keeps your vendor/ to yourself.

CoursePHP for WordPress Developers · Module 5 of 9 · Stage 2 "Architecture"
LearnNamespaces, PSR-4, composer.json in a plugin and prefixing with Strauss or PHP-Scoper
HowShort lessons with code from real plugins, Terminal practice in the browser, interview questions after every lesson

The idea in one picture

flowchart LR
  A["Plugin A<br/>vendor/lib v7"] --> L["Autoloader<br/>first one wins"]
  B["Plugin B<br/>vendor/lib v6"] --> L
  L --> X["Fatal error<br/>in plugin B"]
  P["Prefixed:<br/>PluginA#92;Vendor#92;Lib"] --> OK["No conflict"]
  classDef step fill:#f5f3ff,stroke:#777BB4,color:#1e1b4b
  classDef key fill:#777BB4,stroke:#4f5b93,color:#ffffff

One PHP process, one class name. Prefixing gives each plugin its own copy.

Before → after

BeforeAfter Module 5
require_once lists for every filePSR-4 autoloading
Function names with a long prefixNamespaces
vendor/ that clashes with other pluginsPrefixed dependencies
Dev tools in the release zipcomposer install --no-dev

You'll be able to answer

  • How does PSR-4 map a namespace to a file?
  • Why do two plugins with the same Composer library conflict?
  • What do Strauss and PHP-Scoper do?