I am just starting to write a piece of open source software that is written procedurally as an alternative to OOP mvc skeletons/frameworks. So, while I could just write my own OOP MVC framework, the intended purpose is to do it all procedurally. This is for learning purposes and for purposes of having a DIY codebase ready for when doing a new project. I'm not fully versed on OOP yet, so I feel like doing it this way is a step in that direction. However, the purpose of this project is to be a procedural alternative so it must be written procedurally (and I'm giving this preface to avoid answers of using OOP).
After starting writing I'm realizing that the code is polluting the global namespace a lot (like procedural code is wont to do).
At first, to solve the problem of polluting the global namespace and minimizing accidental naming conflicts, I decided to prefix the variables and functions used like so:
$prefix_variableName = 'value';
prefix_functionName($var){ return $var; }
Then I realized there are better ways to do this. I have two ideas:
1: Create a global array of closures. This way the only global I've set in the code is the single array.. like so..
$myApp = array(
'var1' => 'value1',
'var2' => 'value2',
'function1' => function($var1){ return $var1; },
'function2' => function($var2){ return $var2; }
//etc
);
2: Create a namespace for the global code at the top of every file.. like..
namespace myApp;
$var1 = 'value1';
function1($msg){ return $msg; }
Are both of these options are possible? Can procedural code be namespaced? Which one of these is the better option for this circumstance, and why? Are there any more options?
You certainly can use namespaces for procedural code. Check the docs to see how it works: http://php.net/manual/en/language.namespaces.basics.php
You should always namespace your code to prevent collision. Using an array of closures might produce unwanted behavior like giving the user the ability to unset the value in the global array and the code expecting the callable errors.