note 103606 deleted from language.namespaces by googleguy
| From: | googleguy@php.net | Date: | Sat, 19 Jan 2013 03:47:50 +0000 |
| Subject: | note 103606 deleted from language.namespaces by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193252@lists.php.net to get a copy of this message | ||
Note Submitter: netmosfera at gmail dot com
----
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();
?>