How should I write new code when the old codebase and the environment uses lots of globals in PHP
- by Nicola Peluchetti
I'm working in the Wordpress environment which itself heavily relies on globals and the codebase I'm maintaining introduces some more. I want this to change and so I'm trying to think how should I handle this.
For the globals our code has introduced I think I will set them as dependencies in the constructor or in getter / setter so that I don't rely on them being globals and then refactor the old codebase little by little so that we have no globals.
With Wordpress globals I was thinking to wrap all WP globals inside a Wrapper class and hide them in there. Like this
class WpGlobals {
public static function getDb() {
global $wpdb;
return $wpdb;
}
}
Would this be of any help? The idea is that I centralize all globals in one class and do not scatter them through the code, so that if Wordpress kills one of them I need to modify code only in one place.
What would you do?