I need to do a task involving a PHP class and some sample code which is supposed to run the class. code bellow.
autoloader.php
<?php
/**
* A basic PSR style autoloader
*/
class AutoLoader
{
protected $dir;
protected $ext;
public function __construct($dir, $ext = '.php')
{
$this->dir = rtrim($dir, DIRECTORY_SEPARATOR);
$this->ext = $ext;
}
public static function register($dir, $ext = '.php')
{
$autoloader = new static($dir, $ext);
spl_autoload_register([$autoloader, 'load']);
return $autoloader;
}
public function load($class)
{
$dir = $this->dir;
if ($ns = $this->get_namespace($class)) {
$dir .= DIRECTORY_SEPARATOR.str_replace('\\', DIRECTORY_SEPARATOR, $ns);
}
$inc_file = $dir.DIRECTORY_SEPARATOR.$this->get_class($class).$this->ext;
if (file_exists($inc_file)) {
require_once $inc_file;
}
}
// Borrowed from github.com/borisguery/Inflexible
protected static function get_class($value)
{
$className = trim($value, '\\');
if ($lastSeparator = strrpos($className, '\\')) {
$className = substr($className, 1 + $lastSeparator);
}
return $className;
}
// Borrowed from github.com/borisguery/Inflexible
public static function get_namespace($fqcn)
{
if ($lastSeparator = strrpos($fqcn, '\\')) {
return trim(substr($fqcn, 0, $lastSeparator + 1), '\\');
}
return '';
}
}
run.php
<?php
/* Register a basic autoloader */
require_once 'AutoLoader.php';
AutoLoader::register('src');
/* Create a packer */
$packer = new \Candidate\BoxPacker\DeveloperTestPacker();
/* Create some test boxes */
$boxes = [];
// Create your boxes here
/* Add boxes to packer */
$packer->addBoxes($boxes);
/* Create some test items */
$items = [];
// Create your items here
/* Add items to packer */
$packer->addItems($items);
/* Pack */
$packed_boxes = $packer->pack();
/* Output - var_dump is fine */
var_dump($packed_boxes);
i understand that the require statement in run.php loads the autoloader.php script but that is the only thing about this which makes sense to me.
my questions are as follows
1)
what does AutoLoader::register('src');
do?
2)
$packer = new \Candidate\BoxPacker\DeveloperTestPacker();
creates a new packer object, but what is this object? the autoloader.php file does not make any reference to \Candidate\BoxPacker\DeveloperTestPacker().
3)
The lines $packer->addBoxes($boxes);
, $packer->addItems($items);
, $packer->pack();
seam to call the methods addBoxes()
, addItems()
and pack()
of the instance of a class referenced to by $packer
.
However none of these methods appear in the autoloader class in the autoloader.php
file. and even if they did, $packer
references an instance of \Candidate\BoxPacker\DeveloperTestPacker
not an instance of autoloader.
Can someone explain to me what is happening here?