PHP Connections and Transactions: Connection Class

Antonio Silva - Oct 17 '23 - - Dev Community

Why a class for opening a connection?

Having an explicit connection line in the source code and passing it as a parameter is not something positive, because it has specific information from the database, for example in a mysql connection we pass content such as host, user, password being information that should not be there in the application source code. Another problem is when changing the database we would have to go through many files to change the connection settings.

How will it be done?

We will create a class to open connections, so whenever we want to open a new connection we ask this class and we will leave the connection data outside the class in an ini configuration file, so the configuration data will not be in a source code file, improving if we want to change banks.

Example

Step 1 - Directory System:

📦Connection
 ┣ 📂api
 ┃ ┗ 📜Connection.php
 ┣ 📂config
 ┃ ┗ 📜config.ini
 ┣ 📂database
 ┃ ┗ 📜product.db
 ┗ 📜index.php
Enter fullscreen mode Exit fullscreen mode

Step 2 - ini configuration file:

host = 
name = database/product.db
user = 
pass = 
type = sqlite
Enter fullscreen mode Exit fullscreen mode
  • host : database hosting location
  • name : database name
  • user : database access user
  • pass : database password
  • type : database used
  • port : database port

Step 3 - Connection Class:

<?php

namespace api;

use Exception;
use PDO;

class Connection
{
    private function __construct()
    {
    }
}

Enter fullscreen mode Exit fullscreen mode
  • open method
    /**
     * the open function receives the name of the configuration 
     * file and returns a PDO connection
     * */
    public static function open(string $name): PDO
    {
    }

Enter fullscreen mode Exit fullscreen mode
  • check file
// Checks if the received file exists
if (file_exists("config/{$name}.ini")) {
    // Reads the file and returns a vector with the file data
    $db = parse_ini_file("config/{$name}.ini");
} else {
    // Throw an exception if the file is not found
    throw new Exception("Arquivo {$name} não encontrado");
}
Enter fullscreen mode Exit fullscreen mode
  • Read the file information
// Use isset() to check if information has been set
$host = isset($db['host']) ? $db['host'] : null;
$name = isset($db['name']) ? $db['name'] : null;
$user = isset($db['user']) ? $db['user'] : null;
$pass = isset($db['pass']) ? $db['pass'] : null;
$type = isset($db['type']) ? $db['type'] : null;
Enter fullscreen mode Exit fullscreen mode
  • Check database type
// Check database type
switch ($type) {
    // if the database is PostgreSQL
    case 'pgsql':
        break;

    // if the database is MySQL
    case 'mysql':
        break;

   // if the database is SQLite
   case 'sqlite':
       break;
}
Enter fullscreen mode Exit fullscreen mode
  • PostgreSQL connection
// set the port
$port = isset($db['port']) ? $db['port'] : '5432';
// open connection
$conn = new PDO("pgsql:dbname={$name}; user={$user};
password={$pass}; host={$host}; port={$port}");
Enter fullscreen mode Exit fullscreen mode
  • MySQL connection
// set the port
$port = isset($db['port']) ? $db['port'] : '3306';
// open connection
$conn = new PDO("mysql:host={$host}; dbname={$name}; 
port={$port}", "{$user}", "{$pass}");
Enter fullscreen mode Exit fullscreen mode
  • SQLite connection
// open connection
$conn = new PDO("sqlite:{$name}");
Enter fullscreen mode Exit fullscreen mode
  • return connection
// set exception control
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

// return PDO connection
return $conn;
Enter fullscreen mode Exit fullscreen mode

Testing

<?php

require_once 'api/Connection.php';

use api\Connection;

try {
    $conn = Connection::open('config');
    var_dump($conn);
} catch (Exception $e) {
    print $e->getMessage();
}

Enter fullscreen mode Exit fullscreen mode
object(PDO)[1]
Enter fullscreen mode Exit fullscreen mode

result displayed by var_dump.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .