Me gustaría ver que les parece la siguiente clase que escribí cuando leí sobre namespaces e hice esto como un ejercicio básico de POO. Si ven errores o pueden hacer alguna crítica constructiva, se lo agradecería. :)
Traté de hace un autoloader que usara Namespaces. Usando paths independientemente del SO. Usando el SPL Stack para autoloaders. Funcionara con include_path's. Y que fuese algo personalizable o independiente.
Hice la estructura de directorios:
application\
-library\
--core\
---Test.php
--AutoLoader.php
public\
-index.php
Objetivo: La autocarga de la clase Test.php desde index.php con Namespaces que tengan una relación 1:1 con la estructura de directorios.
Sin más el código de los 3 archivos:
(application\library\Autoloader.php)
Código PHP:
Ver original<?php
namespace Library {
class AutoLoader {
private $autoloader;
private $path;
private $ext;
public function __construct($autoloader = "defaultLoader", $path = null, $ext = ".php") {
if (isset($autoloader)) { $this->setAutoloader($autoloader);
}
$this->setPath($path);
}
$this->setExt($ext);
}
}
// include_path Path Setter & Getter
public function setPath($param) {
$this->path = $param;
}
public function getPath() {
if (isset($this->path)) { return $this->path;
}
}
// SPL Extension Setter & Getter
public function setExt($param) {
$this->ext = $param;
}
public function getExt() {
return $this->ext;
}
}
// Concrete autoloader Setter & Getter
public function setAutoloader($param) {
$this->autoloader = $param;
}
public function getAutoloader() {
if (isset($this->autoloader)) { return $this->autoloader;
}
}
// Callback function of spl_autoload_register
public function autoloader($className) {
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className); // Path now uses DS $className = ltrim($className, __NAMESPACE__
. '\\'); // We cut the string to reflect the route that truly maps with the namespace defined in this class with the filepath. $this->{$this->autoloader}($className);
}
public function concreteLoader($className) {
require_once '\\zf\\ZendFramework-1.11.4\\library\\' . $className . '.php'; // Windows Based Concrete Autoloader (SO DS Dependent) - Ignoring the use of the include_path cause its an absolute path.
} // C:\zf\ZendFramework-1.11.4\library\
public function defaultLoader($className) {
require_once $className . '.php'; // Direct require or looking include_path paths.
}
}
}
?>
(application\library\core\Test.php)
Código PHP:
Ver original<?php
namespace Library\Core {
class Test {
public function __construct() {
echo "La clase " . __CLASS__ . " se ha ejecutado correctamente.";
}
}
}
?>
(public\index.php)
Código PHP:
Ver original<?php
require '..\Application\Library\AutoLoader.php'; // Cargamos el autoloader
$loader = new Library\AutoLoader();
$test = new Library\Core\test();
?>