Listing all objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    Listing all objects

    I like to cleanly handle the destruction of all objects on script termination.
    This is very useful when developing because I can 'round up' all the errors
    even when the script fails.

    At the moment I am explicitly naming the objects in a shutdown function
    and accessing them globally: Example
    Code:
    function shutdownFunc()
    {
        	global $mysql;
    	if(is_object($mysql))
    		disconnectDB($mysql,$errorlist);
    
    	global $mssql;
    	if(is_object($mssql))
    		disconnectDB($mssql,$errorlist);
    }
    This works but requires a shutdownFunc() for every project
    because diiferent objects are created..
    I am now working on the idea of making shutdownFunc() a top-level class::method
    used by all projects but this means finding all objects dynamically.

    The closest I can think is using get_defined_var s() then is_object().
    Is there a better way or even a better idea?
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    if you're using PHP 5 you can make use of the __destruct() method.

    say we're using PDO for DB connection:
    Code:
    abstract class MyDB // implements DB_connector
    {
    	/**
    	 * @var (object) $PDO           PDO DB object
    	 * @var (array) $PS             PDOStatement object storage array
    	 * @var (string) $DB_NAME       DB table name
    	 */
    	private static $PDO      = NULL;
    	private static $PS       = array();
    	public  static $DB_NAME  = MY_DB_NAME;
    	
    	/**
    	 * @desc close DB connection on script end
    	 * @return (void)
    	 */
    [B]	public function __destruct()
    	{
    		self::$PDO = NULL;
    	}[/B]
    
    	/**
    	 * @desc connect to the DB using PDO in a Singleton like pattern.
    	 * @return (void)
    	 * @thrown (Exception)
    	 */
    	public static function connect()
    	{
    		if (self::$PDO === NULL)
    		{
    			try {
    				$dsn = 'mysql:host=' . DB_SERVER . ';dbname=' . self::$DB_NAME;
    				self::$PDO = new PDO($dsn, DB_USER, DB_PASS);
    			}
    			catch (PDOException $pdo)
    			{
    				ErrorLog::logException($pdo, __METHOD__); // my error logger
    				throw new Exception("Connecting to MySQL failed."); // rethrow Exception, because we can't proceed without DB
    			}
    		}
    	}
    
    	// other methods coming here
    }

    Comment

    Working...