wickywills
1/11/2018 - 2:02 PM

PHP class framework with autoloader

Within default PHP file, e.g. index.php, call the autoloader:

require_once('autoload.php');

PHP autoloader example using SPL (taken from http://www.php-fig.org/psr/psr-4/examples/):

spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Lumberjack\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/src/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

Class framework (call the file the same name as the class, so SiteBanner.php):

namespace Lumberjack\ClientName;

/**
 * Banner
 * If there are banners added to the Banner custom field, then use that,
 * if not, fall back to using the page title with a gradient or featured image
 */
class SiteBanner 
{
    /**
     * The page ID of the banner
     *
     * @var Integer
     */
    protected $id;
    
    
    /**
     * Type of banner e.g carousel
     * 
     * @var String
     */
    protected $bannerType = false;
    
    
    /**
     * Contains all the banners swiped from the custom field
     * 
     * @var Array
     */
    protected $bannerItems = [];
    
    
    /**
     * Any special classes that have been applied to the banner 
     * 
     * @var Array
     */
    protected $bannerClasses = [];
    
    
    /**
     * Banner singular title - if the banner repeater field is unused
     * 
     * @var String
     */
    protected $bannerSingularTitle;
    
    
    public function __construct($id) {
        $this->id = $id;
                
        // If the ID wasn't provided, get the current page ID
        if( !$this->id ){
            $this->id = 22;
        }
    }
    

    public function buildBanner() {
        
        // Build banner
        return $banner;
    }
    
    
    public function getClasses(){
        return $this->bannerClasses;
    }
}

Where you need to use the class, ensure you provide the namespace:

use Lumberjack\ClientName\SiteBanner;
$siteBanner = new SiteBanner($id);
echo $siteBanner->buildBanner();