I am wondering the best way to setup a database class, to remove repeat code by using OOP. This way if I changed how I connect to the database (switch from PDO to sqlsrv driver) I can just change it in 1 file, instead of all the files that use PDO. I've setup a class that I will show below, but I feel like it may be hard to understand if I hired a developer in the future.
Also, would it be better to have pre-built functions for returning specific data (.getFriends()
)? I also am going to be using mainly stored procedures, which means, should I create specific functions for doing that? Just to make it more clear to a developer? As you can see, I understand how to do all of this, I am just not sure what a good, clean way is.
<?php
$database = new Database;
class Database
{
public $database;
public function __construct()
{
$this->database = new PDO("sqlsrv:Server=$IP;Database=$DBNAME", "$UsrName", "$Password");
}
// get rows
//Returns rows from specified query. If no bindParams, then pass empty or undefined variable.
public function selectRows($query, $bindParams, $fetchMode)
{
$stmt = $this->database->prepare($query);
$stmt->execute($bindParams);
return $stmt->fetchAll($fetchMode);
}
// insert row
public function insertRows($query, $bindParams)
{
try {
$stmt = $this->datab->prepare($query);
$stmt->execute();
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
// update row
public function updateRows($query, $bindParams)
{
$this->insertRow($query);
}
// delete row
public function deleteRows($query, $bindParams)
{
$this->insertRow($query);
}
}
?>