Creating a databaseDo () function to connect PDO queries

So, I started this tutorial as an introduction to PHP PDO. So far, I have only worked with basic type queries mysql_*.

I noticed that throughout the lesson the pattern connect -> do action -> disconnectrepeats, and only a part do actionever changes.

In a real situation, would it be a good idea to eliminate repetition by creating a function to which requests can be passed?

For instance:

function for processing requests:

<?php
function databaseDo($action) {
    $db_hostname = 'localhost';
    $db_username = 'root';
    $db_password = 'root';

    try {
        // Establish DB connection
        $dbh = new PDO("mysql:host=$hostname;dbname=mysql", 
                $db_username, $db_password);
        echo 'Connected to database';

        // Do something
        $action($dbh);        // <- here goes whatever action we wish to perform

        // Close connection
        $dbh = null;
    } 
    catch(PDOException $e) {
        echo $e->getMessage();
    }
?>

Then suppose that I want to perform the action in the first example of a PDO tutorial, I would set it as follows:

<?php
// Define action
$insert = function($dbh) {
    $query = "INSERT INTO animals(animal_type, animal_name)
                VALUES ('kiwi', 'troy')";
    $exec = $dbh->exec($query);
    echo $exec; 
};

// Perform action
databaseDo($insert);
?>

Volume $ dbh

I am using $ dbh as an argument. Is this the right way to pass a variable to such a function without making it global?

+5
source
2

, , singleton. -

abstract class DB
   {

    protected static $instance;

    protected $db;

    protected static $host = 'host';
    protected static $user = 'user';
    protected static $pass = 'pass';
    protected static $database;

    public static function getInstance()
    {
        if (!isset(self::$instance)) self::$instance = new static();

        return self::$instance;
    }

    public static function doStatement($statement, array $parameters)
    {

         $handler = self::sql()->prepare($statement);
         $handler->closeCursor();
         $handler->execute($parameters);
         return $handler;
    }
    protected function __construct()
    {
        $this->db = new PDO(sprintf('mysql:host=%s;dbname=%s', static::$host, static::$database), static::$user, static::$pass);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

    }

    public static function db()
    {
        return static::getInstance()->db;
    }
}

class Main extends DB
{
    protected static $database = 'db';
}

$db = Main::getInstance();
$results = $db::doStatement('SELECT * FROM table WHERE id = :id', array(':id' => 5));

, ( , / ..), - .

+4

, (DRY) , , , (SoC, . SRP). , databaseDo ($ action), : (1) (2) .

: "! , ! !", . , , , , , .

, - , , . , , . databaseDo() , , , "do", . :

$context = 'production'; // but it could equally be 'development'

function databaseDo($action) {
  $db_hostname = ($context == 'production') ? 'http://remotehost.com' : 'localhost';
  $db_username = ($context == 'production') ? 'apache' : 'root';
  $pass = ($context == 'production') ? 'productionpassword' : 'developmentpassword';

  try {
    $dbh = new PDO("mysql:host=$db_hostname;dbname=mysql", $db_username, $db_password);
    echo 'Connected to database';

    if($context == 'production') {
      // ... some complicated logic to determine whether the production db 
      // will support your query, then execute it if so, exit if not ... 
    }

    if($context == 'development') {
      // ... some more complicated logic for testing and querying the 
      // development db ...
    }

    $dbh = null;
  } catch(PDOException $e) {
    echo $e->getMessage();
  }
}

, .

DRY , , Singleton ( ) . , - . , , Singleton.

+1

All Articles