"Connection Pool" using Static Class

Discussion in 'PHP' started by Jake14, Aug 5, 2008.

  1. #1
    I have an idea, but I'm not sure if it's possible

    Using a static Class, that stores a static variable representing a mysql database connection. The file will be Pool.php

    Then in DIFFERENT php files, say ClientA.php and ClientB.php

    inside they would call

    Pool::getConnection()

    which returns a that single static mysql db connection.

    Do static classes/variables work like this? That is, across files (with proper include statements in ClientA and ClientB)
     
    Jake14, Aug 5, 2008 IP
  2. ahowell

    ahowell Peon

    Messages:
    38
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Pool.php

    class Pool
    {
        
        protected $_dbConn;
        protected static $_instance = null;
        
        
        public function __construct() {
            // make a connection
        }
        
        public static function getDbConn()
        {
            return self::getInstance()->_dbConn;
        }
    
        public static function getInstance()
        {
            if (self::$_instance === null) {
                self::$_instance = new self();
            }
            
            return self::$_instance;
        }
    }
    PHP:

    ClientA.php
    
    // At some point Pool.php will need to be included
    require_once 'Pool.php'
    
    $dbConn = Pool::getDbConn();
    // Do something
    PHP:
     
    ahowell, Aug 5, 2008 IP
  3. Jake14

    Jake14 Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks! works like a charm
     
    Jake14, Aug 6, 2008 IP
  4. JMen

    JMen Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Make static class and static method to do dynamic request? :) Why so? You may do static request to property from static function.

    class Pool
    {
        protected $_dbConn = null;
       
        public static function getDbConn()
        {
    
            if (self::$_dbConn === null) {
    //do connection
                self::$_dbConn = $connection_link; // save connection to link
            }
    
            return self::$_dbConn;
        }
    }
    
    PHP:
     
    JMen, Aug 6, 2008 IP