Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Namespaces and Autoloading: Improving WordPress...

Namespaces and Autoloading: Improving WordPress Plugin Architecture

How to use namespaces and autoloading to improve your WordPress plugin architecture.

Tom McFarlin

March 18, 2017
Tweet

More Decks by Tom McFarlin

Other Decks in Programming

Transcript

  1. HEY, WHAT’S UP? • I’m Tom (Nice to meet you)

    • Suburbia Atlanta • Pressware • Life Outside WordPress
  2. THEY AREN’T BORING • Improved Code • Better Organization •

    Increased Maintainability • Easier Debugging • More Money! (Maybe.) “Boring conversation anyway.”
  3. WHAT ARE THEY? • Plugin conflicts • Weird warning messages

    • Unable to activate a plugin • `class_exists` Namespaces
  4. The PHP Manual http://php.net/manual/en/language.namespaces.rationale.php “Namespaces are designed to solve two

    problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions…”
  5. “A way to group related classes and interfaces having a

    similar purpose.” WordCamp Atlanta 2017 A Working Definition
  6. A PRACTICAL EXAMPLE • You’re working with files. • Classes

    for reading, • Classes for writing, • You may have interfaces, • And so on.
  7. ON FILE ORGANIZATION • It’s not required; it helps. •

    Logical Organization • Virtual Organization • Aim For Both. Please.
  8. NOTES ON NAMESPACES • You can’t just use `new.` •

    Use the fully-qualified name. (The what?)
  9. The PHP Manual http://php.net/manual/en/language.oop5.autoload.php “The spl_autoload_register() function registers any number

    of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.”
  10. “A way to automatically load interfaces and classes without using

    include and require statements.” WordCamp Atlanta 2017 A Working Definition
  11. A PRACTICAL EXAMPLE • Your files are organized. • You’re

    ready to load them. • Let’s do it automatically! • Autoloading, right?
  12. WRITING AN AUTOLOADER • It’s not fully automated. • We

    have to write it. • But once done, it’s done. • It can be reused!
  13. ON AUTOLOADING • Where are the files? • How are

    the files named? • Check if the file exists.
  14. STEPS FOR AN AUTOLOADER 1. Look at the argument 2.

    Parse the namespace(s) 3. Is it an interface or a class? 4. Does the file exist? 5. Include the file.
  15. WHERE TO FIND MORE • My Website • https://tommcfarlin.com •

    SpeakerDeck • https://speakerdeck.com/tommcfarlin • GitHub • https://github.com/tommcfarlin