Using static in PHP

Posted by nischayn22 on Programmers See other posts from Programmers or by nischayn22
Published on 2012-05-30T19:07:41Z Indexed on 2012/05/31 10:49 UTC
Read the original article Hit count: 233

Filed under:
|

I have a few functions in PHP that read data from functions in a class

readUsername(int userId){
$reader = getReader();
return $reader->getname(userId);
}

readUserAddress(){
$reader = getReader();
return $reader->getaddress(userId);
}

All these make a call to

getReader()
{
require_once("Reader.php");
static $reader = new Reader();
return $reader;
}

An overview of Reader

class Reader{
getname(int id)
{
//if in-memory cache exists for this id return that
//else get from db and cache it
}

getaddress(int id)
{
 $this->getname(int id);
 //get address from name here
}

/*Other stuff*/

}

Why is class Reader needed The Reader class does some in-memory caching of user details. So, I need only one object of class Reader and it will cache the user details instead of making multiple db calls. I am using static so that it the object gets created only once. Is this the right approach or should I do something else?

© Programmers or respective owner

Related posts about php

Related posts about static