Reputation: 11
I have a class which does some API (REST) functions. I'd like to declare the variable class-wide variable and static, so I won't fetch the data over and over again. (This is what I think in theory, could be wrong) Many methods in the class will need that data.
I am using this type of class but something doesn't look right. It is working, but (this is just an example class, not the real code);
class Some_Process {
private static $tickets = array();
private function _get_tickets () {
if(!self::$tickets) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, 'http://someurl');
self::$tickets = json_decode(curl_exec($curl));
if(!self::$tickets) {
return FALSE;
}
return TRUE;
}
}
function process_tickets () {
self::_get_tickets();
//here I start using the varible
do some job on .. self::$tickets;
}
}
Upvotes: 1
Views: 743
Reputation: 10645
There is one problem, what if the actual number of tickets returned by http://someurl is zero? then if(!self::$tickets)
will always be true even if we have already filled the array. I would initialize $tickets
with null
:
private static $tickets = null;
and change that condition to:
if( self::$tickets === null ) {
self::$tickets = array();
...
}
Upvotes: 1
Reputation: 4029
And singleton pattern ?
class Some_Process {
protected static $_instance;
private $_tickets = array();
public static function initialiaze() {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, 'http://someurl');
self::getInstance(json_decode(curl_exec($curl));
}
public static function getInstance($tickets = null) {
if (!self::$_instance) {
self::$_instance = new self($tickets);
}
return self::$_instance;
}
private function __constructor($tickets) {
$this->_$tickets = $tickets;
}
public function getTickets() {
return $this->_tickets;
}
public function processTickets() {
$this->_tickets();
...
}
}
with Singleton pattern you instantiate your object one time so you crawl tickets one time.
eq:
Some_Process::initialize();
Some_Process::getInstance()->processTickets();
Upvotes: 0