I have one PHP file named database.php:
try {
$connection= new PDO(DB_DNS, DB_USER, DB_PASS);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo "Error: ".$e->getMessage();
die();
}
and I have a user.php with class Users
:
require_once(__DIR__."/../includes/config.php");
require_once(__DIR__."/../includes/database.php");
class User
{
public function pronadjiSveUsere() {
global $connection;
$upit = $konekcija->prepare("SELECT * FROM users");
$rezultat_upita = $upit->execute();
return $rezultat_upita;
}
public function find_by_id($id = 0) {
try {
global $connection;
$upit = $konekcija->prepare("SELECT * FROM users WHERE id = :id");
$rezultat_upita = $upit->execute(array($id));
return $rezultat_upita->fetch(PDO::FETCH_OBJ);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
}
}
So, you can see that there is a global $connection
in each of the methods. Is this bad and why? If so, what would you do, as parameter passing, or with a constructor?
class User { public function find_by_id($id, $connection) { ...
, right? \$\endgroup\$$connection
to be aPDO
instance). 2) You don't want the caller to have to pass a DB connection for each method. Dependency Injection is what you really ought to be going for 3)PDO::prepare
returns an instance ofPDOStatement
, which is reusable, your code doesn't take advantage of that fact. 4)try {} catch() { die;}
is code smell: catch an exception if you know how to handle that exceptional case, if not: let the exception propagate to code that does \$\endgroup\$