for example, if you use a lot of .php files (once per class) you need to know that require() a lot of files will slow down consistently the page load
so you can use namespaces + autoload to implement package-specific initialization handlers
i used this to put an entire package (lot of classes) in one php file
!!! please note you can't use this as-is but you need to adapt it to your project
the file __init.php is placed inside every namespace/folder you want to load
there you can startup your namespace, check for environment, debugging, or as i do, you can merge all the package in one php file and require it to load other classes too.
<?php
class Loader
{
// here we store the already-initialized namespaces
private static $loadedNamespaces = array();
static function loadClass($className)
{
// we assume the class AAA\BBB\CCC is placed in /AAA/BBB/CCC.php
$className = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $className);
// we get the namespace parts
$namespaces = explode(DIRECTORY_SEPARATOR, $className);
unset($namespaces[sizeof($namespaces)-1]); // the last item is the classname
// now we loops over namespaces
$current=""; foreach($namespaces as $namepart)
{
// we chain $namepart to parent namespace string
$current.='\\' . $namepart;
// skip if the namespace is already initialized
if(in_array($current, self::$loadedNamespaces)) continue;
// wow, we got a namespace to load, so:
$fnload = $current . DIRECTORY_SEPARATOR . "__init.php";
if(file_exists($fnload)) require($fnload);
// then we flag the namespace as already-loaded
self::$loadedNamespaces[] = $current;
}
// we build the filename to require
$load = $className . ".php";
// check for file existence
!file_exists($load) ?: require($load);
// return true if class is loaded
return class_exists($className, false);
}
static function register()
{
spl_autoload_register("Loader::loadClass");
}
static function unregister()
{
spl_autoload_unregister("Loader::loadClass");
}
}
Loader::register();
?>
Espacios de Nombres
Table of Contents
- Visión general de los espacios de nombres
- Definir espacios de nombres
- Declarar subespacios de nombres
- Definir múltiples espacios de nombres en el mismo archivo
- Usar espacios de nombres: Lo básico
- Espacios de Nombres y características dinámicas del lenguaje
- La palabra clave namespace y la constante __NAMESPACE__
- Usar espacios de nombres: Apodar/Importar
- Espacio global
- Usar espacios de nombres: una alternativa a funciones/constantes globales globales
- Reglas de resolución de nombres
- FAQ: cosas que se necesitan saber sobre los espacios de nombres
netmosfera at gmail dot com
22-Apr-2011 06:09
