rtheunissen
rtheunissen

Reputation: 7435

Should global helper functions be namespaced?

Let's say I have some helper functions, for example a̶r̶r̶a̶y̶_̶r̶e̶d̶u̶c̶e̶ 'array_operation'.

Should I declare this function in the global namespace and use it alongside the core array_* functions or should I use it under a vendor specific namespace like use function Vendor\Helpers\Arrays\array_operation;

The only downside of global namespace is that it might be unclear where a function was declared, but also means that you don't need to explicitly use the function whenever you want to use it.

Which would be considered better practice?

Upvotes: 0

Views: 61

Answers (1)

deceze
deceze

Reputation: 522024

The reason for namespacing code is to avoid naming collisions with code from other vendors. This can equally happen for classes as it can for functions or constants (or variables, but nobody uses global variables, riiiight?). The fact that your functions are "helper functions" is irrelevant, they're still functions. Actually, "helper functions" tend to have rather general names, and are therefore all the more likely to clash with other names. So: yes, namespace them.

You may in fact think about maintaining them as an entirely separate package, if that makes sense. One of my personal favourites in this category is Functional PHP, a very nice package of "helper functions" all centred around the premise of providing functional primitives.

Upvotes: 1

Related Questions