PHP Tutorial: Namespaces in PHP code

Source: Internet
Author: User
Tags aliases definition functions php class php and php code php tutorial domain name

The namespaces introduced in PHP V5.3 are a way to provide a context for PHP classes, constants, and functions so that elements that use the same name can be treated as unique. The unique name avoids naming conflicts, which occurs when two classes or functions use the same name. Sometimes these PHP classes represent the same objects in the real world, but their behavior is completely different. Namespaces ensure that you have the correct PHP classes, constants, or functions, and that people who want to use your PHP class can make sure that they use the correct class.

Namespaces in code are like contexts in the real world. Consider a class that represents a real-world car object. For example, a class used by a company that sells cars over the Internet Automobile may behave differently from the classes used by the insurance sales company Automobile .

As an application developer, you might use a component written by someone else. You cannot guarantee that others will never use the name of the class that you have already used, but these classes behave differently. Before a namespace is present, a PHP developer typically constructs a context into a class name, such as My_Enterprise_Person or XML_Validator .

Listing 1 shows a class in the namespace.


Listing 1. Declaring a class in a namespace
				
<?php
namespace IBM;
Class Foo {
...
}
?>

Here's an example that shows how to reference a class in a namespace.


Listing 2. Referencing a class in a namespace
				
<?php
$foo = new \ibm\foo ();
?>

It is a good idea to define a namespace policy before adding namespaces to all classes. Although namespaces can be built up to some extent, it is best to identify a common structure for namespaces to facilitate the organization of namespaces and reduce the modifications that may be required later. Namespaces can also be used to organize PHP code, as long as it is used correctly, in addition to providing context.

Other languages, such as Java™ and C #, used namespaces long ago. In choosing a namespace naming method, the conventions I use are similar to those of these languages because many developers are familiar with it and make it easier for them to understand. However, unlike the Java language, there is no connection between the namespace in PHP and the directory where the class resides. You can select any namespace for a class, function, or constant. You can even use more than one namespace for a file. Also, the PHP namespace is different from C #, and you can use namespaces for functions or constants other than classes.

Top-level namespaces

If you are building namespaces for an organization, you can use the organization name as the top-level domain. In general, creating a top-level namespace by using an organization name is sufficient to provide context for the PHP code and to avoid naming conflicts unless the organization writes a large number of applications that are of different uses.

The example in Listing 3 shows how to declare a top-level namespace.


Listing 3. Top-level namespaces
				
<?php
namespace IBM;
...
?>







Secondary namespaces

The secondary namespace is the namespace inside the top-level namespace. They provide further instructions when the top-level namespaces are not enough to create a context for the PHP class.

When creating a secondary namespace, it is important not to create it too much with a momentary interest. As the number of secondary namespaces increases, it becomes increasingly difficult to organize and reference them. If you want namespaces to play a dual role, avoiding naming conflicts and organizing PHP code, you need to pay more attention to this.

When deciding how many secondary namespaces should be introduced to another namespace in order to facilitate organization code, I tried to limit the number to 7 (up and down no more than 2) to make use of the number 7 to remember this advantage more easily. This does not always work, but I use it as a guideline to ensure that namespaces are not divided into too many secondary namespaces.

The example in Listing 4 shows the declaration of a secondary namespace in the top-level namespace.


Listing 4. Secondary namespaces
				
<?php
namespace Ibm\developerworks;
...
?>

The backslash ( \ ) separates the secondary namespace "DeveloperWorks" from the top-level namespace "IBM".

When declaring a secondary namespace, you can use two common techniques, or use them at the same time. A common place to get a namespace is a project name or application name, and another place is a domain name.

Through the project definition

If you use the organization name as the top-level namespace, and you want to provide further context through the secondary namespace, you can use the project name or application name as the secondary namespace. For example, if you build a new application called Greeter (to get the user's name and greet them), the namespace in Listing 5 will Prompt provide the full context for the class called.


Listing 5. Use the application name as the secondary namespace
				
<?php
namespace Ibm\greeter;
Class Prompt {
...
}
?>

Because it Prompt may be the class name of more than one application or library, adding an organization name and a project name to the namespace allows the class to be Prompt distinguished from other classes with the same name.

by domain definition

Using a domain name is another common way to select a secondary namespace, as shown in Listing 6. It can also be used after the project name and whether it depends on your plan for reusability (see "Naming according to Reusability").

A domain is a set of classifications for a larger problem domain. An example of a domain is the "account", "Customers" or "product" of accounts, customers, and products that are processed in larger applications.


listing 6. Using a domain as a secondary namespace
				
<?php
namespace Ibm\myapp\account;
Class Address {
...
}
?>







Naming according to Reusability

In addition to the application of modular concepts that support reusability, the naming of classes and namespaces can be reusable. Sometimes bad naming can compromise reusability, because bad names imply that classes can only be used for specific purposes. Similarly, incorrectly applying namespaces may unnecessarily limit the use of classes and make them more difficult to reuse.

In the top-level namespace that uses the organization name, you should preserve namespaces that can be reused across applications, such as "Common", "Core", "Lib", and so on. A common example is validation, where the rules for an entire enterprise inventory unit (SKU), account number, or invoice number are the same, obtaining the appropriate rules and lengths. For the Validator class, a namespace like Listing 7 is a good choice.


Listing 7. Using the generic validation namespace
				
<?php
namespace Mycompany\common\validation;
Class Notnullvalidator {
...
}
?>

Here, the organization name is used as the top-level domain ("MyCompany"). The "Common" namespace is used as a project. Even if you are writing a particular application, you may be writing a class that can be used in any project in your organization. Finally, "Validation" is used as the domain of the class.







Using aliases

Although namespaces can help you organize classes and avoid naming conventions, the disadvantage is that the name is too long. Fortunately, PHP supports the use of aliases, so you can use shorter aliases in your code. Listing 8 provides an example.


listing 8. Using aliases
				
<?php
Use mycompany\common\validation as validators;
?>







Naming conventions

Namespace naming uses the word initials or PASCAL naming conventions, as with other PHP conventions, such as the PHP Extension and application Repository (PEAR) package naming and file names. For example, the namespace in Listing 9 is better than the namespace in Listing 10.


Listing 9. The first letter of the word or PASCAL named
				
<?php
namespace MyNamespace;
?>

Avoid naming and capitalization conventions that conflict with other PHP conventions.


listing 10. Using Bad capitalization conventions
				
<?php
namespace MyNamespace;
...
?>





Conclusion

Namespaces in PHP can be used to organize code, avoid naming conflicts, and provide context for classes, functions, and constants. Using patterns or conventions in namespaces makes your code easier to understand and easier to reference and use.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.