Namespaces are a feature of several systems and development languages including PHP. What do they really do, compared to the wild claims of the attention seekers?
The examples here are based on PHP and the principles apply to most types of namespaces out there. Namespaces were added to the PHP language in PHP 5.3. Prior to that, many software development projects definded namespaces as part of their conventions.
What is a namespace?
Think of your address. You live in 59 Smith Street, Springfield. The city, or suburb, Springfield, is a namespace. There is only one Smith Street in Springfield and the Smith Street in Springfield is different to the Smith Streets in other suburbs.
Suburbs and cities are not rigid namespaces, some cities let developers use the same street name in different areas. When you compare large cities, some cities make their street names unique within a suburb but addresses are then accepted with area names that are not suburb names. One street may run through several suburbs.
Computer namespaces have the advantage of automated checking to ensure there is no duplication. If the namespace is connected to a file system, the file system will prevent the storing of duplicates. You cannot have two files with the same name. If programs or classes or functions are always stored in files using the same name, you cannot store a duplicate.
Well, not in Windows because windows uses a semantically correct file system. Linux and Unix are still a problem. Take the example of a file named demo.txt. If you accidentally type the file name as Demo.txt, Linux and Unix will store the file as a different file to demo.txt. Linux and Unix need major repair work to make them namespace compatible.
What does a namespace look like?
Use the example of a module added to an application. Give the module the name of tax_calculation. Assume the module contains a function named add_gst. A common convention, from before namespaces, is to name the function tax_calculation_add_gst to make sure it is unique within the application.
Your namespace version of the code will define tax_calculation as the namespace using the following line of code.namespace tax_calculation;
Your development system, framework, or application will require the code stored in a directory to match the namespace. Create the following directory where required.tax_calculation/
Your add_gst function is stored in a file named add_gst.php. Your development system, framework, or application may require the file name to include the word function as an additional identifier, as shown next.add_gst.function.php
The path to your add_gst code is shown next.tax_calculation/add_gst.function.php
You would assume namespaces would use tax_calculation as the namespace and gst as the name within the namespace. Some systems and frameworks split tax_calculation into tax and calculation, plus the split add_gst into add and gst. The path to your code may become the following complication.tax/calculation/add/gst.function.php
Speedbump
Another complicated approach is to use the semantically incorrect system of trying to define structure through the use of decorative capital letters. The following path shows your readable path converted to speedbumps.taxCalculation/addGst.function.php
The speedbump naming convention might be called bumpy case, camel case, capsh*t, studlycaps, or some other name depending on the frustration of the person trying to work with it. Half of the speedbump world demand addGst, half demand AddGst, and the other half demand something different. Yes, I know that does not add up. Speedbump addicts often demand different bumps mixed together in the hope that each pattern will mean something special.
Consider the following identifier displayed in several ways. The all have the same meaning to everyone but some operating systems, some file systems, some programming languages, and developers pretend they have different meaning but then they say no, only some of the decorations have meaning.
sweetpotato
sweetpotato
sweetPotato
sweetpotato
sweetpotato
SweetPotato
SweetPotato
Use a namespace
Create a directory named example. Create a file named sample.function.php in the directory. Here is the file content:
<?php
namespace example;
function sample()
{
return 'Yea, it worked!';
}
?>If you have to comply with PSR-1, you will have to degrade the format to something like:
<?php
namespace example;
function sample()
{
return 'Yea, it worked!';
}Developers contributing to old systems, including Drupal before Drupal 8, will have to degrade the format further:
<?php
namespace example;
function sample() {
return 'Yea, it worked!';
}There are only two rules to remember:
- Nothing is allowed before the namespace definition.
- Several things are allowed before the namespace definition.
Tough conflicting rules to follow. Lets work through them.
- The namespace system assumes there will be one namespace per file and that is a good design decision most people already follow without namespaces.
- The namespace system allows more than one namespace per file and
discourages
the idea. - The namespace definition has to be first so PHP, or any other processor, can apply the definition to everything in the file. This is the reason for the
Nothing before
rule. - PHP has to know the namespace definition is PHP code which means the
<?phpidentifier has to be before the namespace definition. - If your code is encoded in a characterset different to everything else, you can specify the encoding with a declare statement:
declare(encoding='ISO-8859-1');The declare has to be before the namespace statement so PHP can read the namespace statement using the right characterset. - No other code or anything else is allowed before the namespace.
- If the file is processed through multiple software or systems, you might need other data at the start, equivalents to the declare for the relevant processors.
- If you use multiple namespaces per file, the second namespace is preceded by the first namespace plus all the code,comments, and everything else in the first namespace.
- Comments are not code and are currently allowed before the namespace definition. This will let version control systems continue to put their status messages at the top of the code.
You can see a few best practices
will help. Only one namespace per file. No HTML in your namespaced files.
Multiple hierachical namespaces
We have the example namespace definition, namespace example;, and decide to include examples named aa and bb, then you expand aa with aa2 and aa3. you can define them with the following definitions.namespace example\aa;namespace example\aa\aa2;namespace example\aa\aa3;namespace example\bb;
The namespace structure can expand forever and is totally unworkable in a few levels unless the levels have meaning. You might have the tax example set up by country code, namespace tax\au; or by type of tax, namespace tax\au;, so long as there is consistency in your overall design.
Expanding on the tax example, if your system already has country specific code in other sections, use that for your tax. The country level can then point back to a common tax processing system if several countries share the same tax system. Life is easier if there is only one namespace by country code.
How do you know where you are in a namespace?
There are times when you need to know the name of your namespace to pass the name to code in another namespace. You can use the following code to get the namespace.$name = __NAMESPACE__;
You can also use the namespace keyword in function names and other places. The following line requests function example_function from the current namespace. In fact both of the following lines do the same thing. There are not many cases where you will use the keyword this way.$x = namespace\example_function();$x = example_function();
What do you do when a namespace is long?
Namespaces can become annoying in length. Assume you are in namespace aa and your code has to refer to functions in namespace games\physics\special_effects\weather\rain. Do you want to continually type games\physics\special_effects\weather\rain\drops();? The following lines show a shortcut in use.use games\physics\special_effects\weather\rain;$x = rain\drops();
Now you can rain as a short local name. What do you do when you have to use the name rain from several namespaces? The following example expands the previous example with two uses of rain.use games\physics\special_effects\weather\rain;use games\physics\special_effects\weather\storm\rain as heavy_rain;$x = rain\drops();$y = heavy_rain\drops();
Do namespaces fix code formatting problems?
No, code formatting problems remain exactly the same. There is a move to fix code formatting standards through a common format but the most popular new standard, PSR-1, is full of holes and is semantically incorrect. Namespaces are another complication because many existing conventions do not allow for namespaces.
The PSR-1 standard, also called PSR-0, advances code formatting from the commonly used but ugly and hard to read Unix bracket/brace format to a more readable format but reduces the name format to studlycaps, except where they have to be camelcase, except where they have to be all caps, except where it says they can be anything because they are excluded from the requirement. So they require one type of name to be uniquely identifiable as a class because it uses camelcase, studlycaps, whatever, but then you are allowed to use exactly the same format for other names.
Namespaces do not cure inconsistency, stupidity, or stop committees writing compromise standards without ever testing the result.
Conversion to namespaces
You can mix namespaces with your current code and evolve into namespaces. Most frameworks and applications burst into a new highly structured namespace system with rigid rules. You have to stop everything for the conversion. You have to rethink all your current names because the are often illegal.
Some systems end up with almost as many directories as files. Finding a file is a pain. You need a wide screen to display the incredibly long paths built by the framework. Some development environments will have to change to let you work in a target area without all the path rubbish above the target. You will need bookmarks into your target areas.









- Facebook Like
- Google Plus One
- Log in or register to post comments