What does the namespace really look like? [duplicate]

5

I would like to realize the great need and utility of namespaces in the MVC architecture.

In what circumstances does the use of namespaces become indispensable?

Give an example of a concrete case if possible.

    
asked by anonymous 07.04.2017 / 15:43

1 answer

10

The main use of namespaces is for organization and to avoid collision of class names. PHP does not allow two classes to have the same name, and to avoid this problem we had to create very specific classes.

The motivator of this was the start of frameworks in PHP, which came as a proposal to solve common problems in development. But that limited how to create our classes, because we could not repeat names. The solution was to create very specific classes, prefixing with the name of your application.

Suppose you are developing a Service class to query freight from a zip code.

Creating a class that is named Service can conflict with another class Service to send SMS.

So, instead of doing this:

App_ConsultCepService

App_SendSmsService

With namespaces you can do something like this:

App\Cep\Service

App\Sms\Service

This also helps you split your software into common interests, as well as using already-established autoloads standards with major PHP projects such as the PSR-4 that is implemented by Composer.

For more explanation see:

How do PHP namespaces work?

PSR-4 in an MVC project or not?

    
07.04.2017 / 15:53