Alexsoyes
Alexsoyes

Reputation: 444

PHP Performance : Is "global" keyword better than "include" in function?

Let's pretend I have a database.php file which contains a persistent access to the database.

<?php
$database = new PDO('mysql:host=xxx', "xxx", "xxx", array(
    PDO::ATTR_PERSISTENT => true
));
?>

Every time I want to query the database within a controller, what should I do?

1/ Use the global keyword to get my global $database variable

<?php

include '../app/config/Database.php';

function getLastOfTheWeek()
{
    global $database;
    $database->query('SELECT * FROM `xxx`');
    ...
}
?>

2/ Include database.php within the function

<?php

function getLastOfTheWeek()
{
    include '../app/config/Database.php';
    $database->query('SELECT * FROM `xxx`');
    ...
}
?>

3/ Give this man some doc, he needs it

Or both are evil anyway, and I should use another method.

Upvotes: 0

Views: 151

Answers (2)

Sammitch
Sammitch

Reputation: 32262

  1. Global state is bad.
  2. Repeatedly creating DB connections is bad.

Good:

$dbh = new PDO (...);

function doSomething($dbh) {
  $dbh->query(...);
}

OK:

class Something {
  protected $dbh;

  public function __construct($db_config) {
    $this->dbh = new PDO($db_config); // still bad
  }

  public function doSomething() {
    $this->dbh->query();
  }
}

God Tier:

class Something {
  protected $dbh;

  public function __construct(PDO $dbh) {
    $this->dbh = $dbh;
  }

  public function doSomething() {
    $this->dbh->query();
  }
}

$dbh = new PDO(...);
$s = new Something($dbh);
$s->doSomething;

See: http://www.phptherightway.com/#dependency_injection

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35337

In this simplified example, the global would be better performance assuming you have multiple functions or function calls as the global would re-use the same connection.

However, this does not mean that including Database.php multiple times is always going to be slower. Assuming you have opcache enabled, including the same file multiple times will have very little overhead. The problem is that you are opening a new PDO connection every time you include this file because of how your code is written.

There are a lot of other solutions that do not involve using a global. DI containers are often used to resolve dependencies at the start of an application. The singleton design pattern could also be beneficial if you always want to re-use the same connection.

Upvotes: 1

Related Questions