天天看點

php 命名空間通俗易懂_PHP: 命名空間概述 - Manual

To people coming here by searching about namespaces, know that a consortium has studied about best practices in PHP, in order to allow developers to have common coding standards.

These best practices are called "PHP Standard Recommendations" , also known as PSR.

They are visible on this link : http://www.php-fig.org/psr

Actually there are 5 coding standards categories :

PSR-0 : Autoloading Standard , which goal is to make the use of Namespaces easier, in order to convert a namespace into a file path.

PSR-1 : Basic Coding Standard , basically, standards :)

PSR-2 : Coding Style Guide, where to put braces, how to write a class, etc.

PSR-3 : Logger Interface , how to write a standard logger

PSR-4 : Improved Autoloading , to resolve more Namespaces into paths.

The ones I want to point are PSR-0 and PSR-4 : they use namespaces to resolve a FQCN (Fully qualified class name = full namespace + class name) into a file path.

Basic example, you have this directory structure :

./src/Pierstoval/Tools/MyTool.php

The namespacing PSR-0 or PSR-4 standard tells that you can transform this path into a FQCN.

Read the principles of autoload if you need to know what it means, because it's almost mandatory ;) .

Structure :

{path}/autoloader.php

{path}/index.php

{path}/src/Pierstoval/Tools/MyTool.php

Files :

classMyTool{}?>

if (false!== ($lastNsPos=strripos($className,'\\'))) {$namespace=substr($className,0,$lastNsPos);$className=substr($className,$lastNsPos+1);$fileName=str_replace('\\',DIRECTORY_SEPARATOR,$namespace) .DIRECTORY_SEPARATOR;

}$fileName.=str_replace('_',DIRECTORY_SEPARATOR,$className) .'.php';$fullFileName=$includePath.DIRECTORY_SEPARATOR.$fileName;

if (file_exists($fullFileName)) {

require$fullFileName;

} else {

echo'Class "'.$className.'" does not exist.';

}

}spl_autoload_register('loadClass');// Registers the autoloader?>

A standardized autoloader will get the class you want to instanciate (MyTool) and get the FQCN, transform it into a file path, and check if the file exists. If it does, it will <?phpinclude ();?> it, and if you wrote your class correctly, the class will be available within its correct namespace.

Then, if you have the following code :

<?php $tool= newPierstoval/Tools/MyTool();?>The autoloader will transform the FQCN into this path :

{path}/src/Pierstoval/Tools/MyTool.php

This might be the best practices ever in PHP framework developments, such as Symfony or others.