We all know that namespacing your application code is a best practice and a PSR recommendation. The only thing PSRs take stance on is the whitespace and side-effects when it comes to functions and their declaration.
But what about functions which are not related to any single class? Should they be namespaced or left in the global namespace?
Some developers are saying that namespacing functions is bad practice but I wasn't able to grasp why.
From what I've learned/read and seen recommended regarding to namespacing functions:
Are there best practices for global functions and namespacing them? Currently I use the application root namespace for global application related functions, but I keep wondering why some people strongly believe no namespacing should happen outside objects (classes, interfaces, traits, etc.)?
The main objective of namespaces is to prevent name collisions, more over they are used to group classes, methods. As you mentioned there are a lot of classes within a Laravel project so namespaces would have to be used to prevent collisions which will happen in big projects.
A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
PHP Has Had Namespaces Since 5.3 Because the basic features of namespaces were added to PHP with 5.3, which came out all the way back in 2009.
Namespaces are a concept that allow you to impose a structure on smaller-scale constructs. With namespaces, you can put things together that belong together. It doesn't matter whether these things are classes or functions. If you have a free function that is only used together with two or three specific classes, I'd certainly put that function in the same namespace as the classes.
Whether or not you want to use free functions at all is a different question. Many OO languages such as Java and C# don't support them. But there are cases where a function just doesn't fit into a class. In these cases, I prefer creating free functions (in the appropriate namespace).
That being said, I'm pretty sure you will get both YES and NO answers here on SO as well. So discuss it with your team, and establish a guideline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With