Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class PDOConnectionFactory{
- public static $instance = null;
- private $debug=1;
- public $conn = array();
- public $persistent = true;
- public $connlimit=5;
- public $connleases=0;
- public $connqty=0;
- public $dbType = "mysql";
- public $host = "localhost";
- public $user = "root";
- public $password = "tyuiopas";
- public $db = "test";
- private function __construct() {
- }
- public function log($message) {
- if ($debug > 0) {
- $timestamp="## NOW ##";
- echo "$timestamp - $message\n";
- }
- }
- public static function getInstance() {
- if (!isset(self::$instance)) {
- // Você deve informar os dados para conexão com o banco de dados.
- self::$instance = new PDOConnectionFactory();
- }
- return self::$instance;
- }
- public function getConnection(){
- $retconn=null;
- if ($this->connleases < $this->connlimit) {
- log("Navega o Pool para achar Conexões existentes\n");
- for ($i=1; $i<=$this->connlimit; $i++) {
- if ($this->conn[$i] != null) {
- //echo "Fornecendo: $i\n";
- $retconn = $this->conn[$i];
- $this->connleases++;
- unset($this->conn[$i]); // Remove Efetivamente a Connection do Array
- break;
- }
- }
- log("Caso não exista no pool, criar uma nova\n");
- if ($retconn == null) {
- try{
- //$newconn = rand(1,1000000);
- $newconn = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->password, array( PDO::ATTR_PERSISTENT => $this->persistent ) );
- $this->connqty++;
- $this->connleases++;
- $retconn = $newconn;
- } catch ( PDOException $ex ) {
- log("Erro: ".$ex->getMessage());
- return -1;
- }
- }
- } else {
- log("Todas conexões alocadas");
- return -1;
- }
- return $retconn;
- }
- public function returnConnection($leasedconn) {
- //echo "Retornando: $leasedconn\n";
- for ($i=1; $i <= $this->connlimit; $i++) {
- // echo "i = : $i conn-i = " . $this->conn[$i] . "\n";
- if ($this->conn[$i] == null) {
- //echo "Guardando em $i\n";
- $this->conn[$i]=$leasedconn;
- $this->connleases--;
- break; // Parar o Loop - foi a melhor idéia que tive :(
- }
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement