7. Namespacing
Let's take a little side journey here and talk about something very fundamental to Yii2: Namespacing. Using namespaces is a way to encapsulate a collection of related items. As a concrete example, the file foo.txt can exist in both directory /home/first and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/first directory, we must prepend the directory name to the file name using the directory separator to get /home/first/foo.txt. This same principle extends to namespaces in programming Yii.
Namespaces in PHP solve two serious problems run into when creating complex software systems that reuse code elements such as classes or functions. You need to keep them straight as to which apply where.
- Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
- Ability to alias (or shorten) Extra_Long_Names that would normally be used to alleviate the first problem, thus improving readability of source code.
An example of a name collision would be if you tried to create your own custom object as:
new DateTime()
You would not be able to because there already exists in PHP a
DateTime
object. This is referred to as a name collision.
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:
file1.php
<?php
namespace yii\foo;
function printout(){
echo ‘Zig’;
}
?>
file2.php
<?php
namespace yii\bar;
function printout(){
echo ‘Zag’;
}
?>
file3.php
<?php
yii\foo\printout() // output: Zig
yii\bar\printout() // output: Zag
?>
Accessing the global namespace What if in file2.php you wanted to use the PHP reserved object:
You would get an error similar to yii\bar\DateTime object not found. To use the PHP defined DateTime object, you will need to express it as this, with a slash:
This places it in the global namespace where PHP defined objects are located. |
7.1 The Use Statement
Let's say you have file4.php and you want to access yii\foo\printout(), but don't want to type out the entire yii\foo\printout() string. You can set up your script as follows:
file4.php
<?php
use yii\foo\printout;
printout() // output: Zig