Dependency Management ● Declare, resolve, and install project-specific dependencies ● Use others’ code ○ Use open source packages ○ Focus on your biz features ○ Avoid “NIH syndrome” ● Create reusable packages in your own org
Before Composer ● Compile PHP with extensions ● System-level package managers ● PEAR packages (system-system) ● Include 3rd-party code in source ● Git submodules Composer inspired by bundler and npm
Specifying Versions MAJOR.MINOR.PATCH (SemVer.org) “{vendor}/{package}”: “{version constraints}” ● “>=3.1.4” – Use any version >= 3.1.4 ● “3.1.*” – Use any patch version of 3.1 ● “~3.2” – Use any 3.x version >= 3.2
Including Classes - Not Fun // NOTE: Assuming one class per file require_once(‘classes/user.class.php’); require_once(‘classes/page.class.php’); require_once(‘classes/role.class.php’); require_once(‘classes/db.class.php’); // ...
What is an Autoloader? 1. A callback triggered when a non-existent class is referenced. 2. A function that provides a definition for a specified class name.
Autoloader Advantages ● Classes are loaded on demand ○ No need to write specific include statements ○ Class never loaded unless it’s needed ● Leads to better code maintainability ● Easy to write
Simple Autoloader Implementation class Autoloader { public function __construct($root) {...} public function load($class) { $path = $path->root; $path .= str_replace(‘\\’, ‘/’, $class); if (file_exists($path)) require $path; } }
Autoloader Implementation Tips ● You can have multiple autoloaders. ● Don’t throw errors/exceptions if a file doesn’t exist. Let the other autoloaders try. ● Don’t use the __autoload() function. ● Use Composer’s autoloader. ○ You don’t have to write your own ○ It already follows the PSR autoloading standards
Autoloader Implementation Revisited class Autoloader { public function __construct($root) {...} public function load($class) { $path = $path->root; $path .= str_replace(‘\\’, ‘/’, $class); if (file_exists($path)) require $path; } }
Autoloader Implementation Revisited class Autoloader { public function __construct($root) {...} public function load($class) { $path = $path->root; $path .= str_replace(‘\\’, ‘/’, $class); if (file_exists($path)) require $path; } }