You are here: Re: Accessing a PDO DB object from within Singleton pattern « PHP Programming Language « IT news, forums, messages
Re: Accessing a PDO DB object from within Singleton pattern

Posted by Michael Fesser on 10/02/07 01:49

..oO(macca)

>Hi, quite new to design patterns so please humour me.
>
>I'm having a little trouble figuring out how to use the singleton
>pattern to create a database PDO object that I can then refer to in my
>script.
>
>[...]
>
>$dbh = PDO_Singleton::getInstance();
>
>
>
>OK, So now I have my instance and i want to use my PDO object, if try
>this:
>
>$statemant = $dbh->_connection->prepare("select * from pans");
>
>Which obviously gives me the message "Cannot access private property
>PDO_Singleton::$_connection" because $_connection is declared private.
>
>
>So how am I supposed to use my PDO object without having to declare it
>public or access it from within my PDO_Singleton class?

Two ways come to mind:

1) Make your singleton class extend the PDO class. This way in the code
above $dbh itself would become the PDO instance, so you could call

$dbh->prepare(...);

2) Use the decorator pattern. The decorator (your singleton) has to
forward all method calls to the decorated object ($_connection), either
by explicitly writing a method for each or by using the magic __call()
interceptor method. I use the latter in my own database class:

protected function __call($method, $arguments) {
return call_user_func_array(
array($this->driver, $method),
$arguments
);
}

(The $driver property would be $_connection in your case.)

Micha

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация