PHP Classes

File: test.php

Recommend this page to a friend!
  Classes of Raul   PHP PDO Connection Factory   test.php   Download  
File: test.php
Role: Example script
Content type: text/plain
Description: Testing file
Class: PHP PDO Connection Factory
Create PDO objects to connect to a database
Author: By
Last change: Adding a "\" on PDO Class (default php namespace)
Date: 10 years ago
Size: 1,317 bytes
 

Contents

Class file image Download
<?php
use Core\lib\db\ConnectionFactory;
/**
 * The test file is in Core folder
 * Place the class on Core/lib/db
 * directory to use autoloading
 */
require_once 'Core/lib/db/ConnectionFactory.php';

$arguments = [
   
'driver' => 'mysql',
   
'host' => 'localhost',
   
'user' => 'root',
   
'password' => '',
   
'database' => 'dbname',
];

/*PHP 5.4+ style - just connect*/
$pdo = (new ConnectionFactory($arguments))->getLink();

/*PHP 5.3- style - just connect*/
$connectionFactory = new ConnectionFactory($arguments);
$pdo = $connectionFactory->getLink();

/**
 * You can use the method getLink or the alias getConnection() as well
 */
$pdo = $connectionFactory->getConnection();

/**
 * You can set any attribute or driver option
 */
// Attributes (will add on setAttribute PDO's method
$connectionFactory->addAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER);
$connectionFactory->addAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
// Driver's option (will add on the fourth parameter on PDO constructor)
$connectionFactory->addDriverOption(\PDO::ATTR_PERSISTENT, true);
$connectionFactory->addDriverOption(\PDO::MYSQL_ATTR_MAX_BUFFER_SIZE, 1024 * 1024 * 10);

$pdo = $connectionFactory->getLink();

/**
 * Now you can use all the PDO's methods!
 */