I have the following global statement calls sprinkled throughout my PHP legacy codebase:
$jobnumber = db_quick($sql);
db_query($sql);
That is, those function calls have been initialized in the global scope and they themselves call upon a previously initialized MySQL global object, i.e:
//initializes MySQL connection object in the global scope
$dblink = MySqlConnector::getMySql();
function db_query($sql)
{
//previously initialized MySQL connection object
global $dblink;
//native MySQL API call:
return mysqli_query($dblink, $sql);
}
Question
Are there any benefits to refactoring these global statements, other than just to say "I have now removed them from the global scope"?
The spirit of my question goes ... those are already in the codebase, and they work. Must I mess with them? So far [3 years working with the code] there has been no apparent harm. Even with transition from deprecated mysql to mysqli, it was a painless transition. Will keeping these as global cause any measurable harm later? Are these good enough to be left as is?
What if I refactor?
By the way if I refactor I am thinking of using a Singleton pattern for database link instantiation and then calling it via an instantiated class, that calls the Singleton. Like so:
//in a calling class:
$repository = new GenericRepository();
$repository->getMySql()->persist($sql);
$value = $repository->getMySql()->paramQuery($sql, $param);
//GenericRepository makes a static call to the actual connector
class GenericRepository
{
final public function getMySql()
{
if ($this->link === null)
$this->link = MySqlConnector::getMySql();
return $this->link;
}
}
//Connector calls MySQL API
class MySqlConnector
{
public static function getMySql()
{
if (null === static::$instance)
{
include 'include/config.php';
//class MySql extends mysqli library
static::$instance = new MySql(DBHOST, DBUSER, DBPASS);
}
return static::$instance;
}
}
So in essence, by refactoring, I will be removing the globals database methods and replacing them with instantiated calls to the Singleton pattern. The code change will be fairly extensive, as there are a couple of thousand of global database calls.
Effects of the above Refactoring
Currently I can call the methods "from anywhere" - they are global.
db_query($sql);
After refactoring I will still be able to call them "from anywhere", but using a longer connection string.
(new \Namespace\GenericRepository())->getMySql()->persist($sql);
That sounds a bit like a detriment - longer string, more to type, more to copy & paste. Are there really some benefits to this?