Search this blog for:

Thursday, December 06, 2007

PHP Singleton design pattern

I think design patterns are stupid, people publish huge books of them, containing things like the singleton - which I think is a pretty basic pattern in Java. And can be implemented using a static self-typed variable and private constructor... hardly seems worthy of its own design pattern to me.

But it does make it easier for me to find this sort of thing in a language I am less familiar with.

This is a very untested implementation of the singleton pattern in PHP. I want to only load the file once. Because that would seem more sensible to me, so the constructor loads the countries list


class survey_countries
{
var $content;

/**
* Create an instance of the survey countries class.
*
* @return survey_countries
*/
private function survey_countries()
{
$temp_file = new common_io_file("../lib/countries_file", /*FILE.*/READ);
$this->content = $temp_file->get_contents();
}

/**
* Return the content array.
*
* @return array
*/
function get_content()
{
return $this->content;
}

/**
* implements the 'singleton' design pattern.
* @return survey_countries
*/
static function get_instance()
{
static $instance;
if (!isset($instance)) {
$instance = new survey_countries();
}
return $instance;
}
}

No comments: