Namespace Functions - Structure - Typed PHP, Stronger Types for Cleaner Code

Typed PHP, Stronger Types for Cleaner Code (2014)

Structure

Namespace Functions

I’ve spoke a bit about how all these global functions are bad, and there’s a really simple alternative: namespace functions. You’ve probably used namespaces, for classes, but the same constructs work well to isolate functions:

1 <?php

2

3 namespace Type\String {

4 function length($string) {

5 return strlen($string);

6 }

7 }

8

9 namespace {

10 print Type\String\length("Hello World");

11 }

Composer Autoload

This kind of function definition doesn’t follow normal autoload patterns. In order to have Composer autoload these kinds of files is to explicitly define which files should be loaded:

1 {

2 "autoload" : {

3 "files" : [

4 "namespace-functions.php"

5 ]

6 }

7 }

Following this, we’ll have to dump the old autoloader, with:

1 $ composer dump-autoload

2

3 Generating autoload files

The files (containing namespace functions) will now be automatically loaded, wherever the Composer autoloader is used.

Future Goodies

PHP 5.6 supports the use function construct, to import functions from other namespaces. It’s currently in beta (at the time of writing), but this feature is right up our proverbial alley.

In the meantime, it’s possible to partially import functions:

1 use Type\String;

2

3 print String\length("Hello World");

This is especially useful for deeply-nested namespace designs. Still; it’s great to be able to omit even a little of the full namespace. The result is clean(er), non-colliding procedural code.

Conclusion

Even today, it’s possible to create a cleaner scalar type system/abstraction. We don’t need special extensions, or compilation steps. Just a little bit of work will clean the code right up.

Having said that, extensions can go a long way towards making our lives easier, while still allowing the level of customisation and unity that we are hoping to achieve. We’ll look at a few of these in the following chapter…