PHP caching class - php

I'm a AS3 coder and i do a bit of php and i am having a hard time doing a static class that can cache variables.
Here's what i have so far :
<?php
class Cache {
private static $obj;
public static function getInstance() {
if (is_null(self::$obj)){
$obj = new stdClass();
}
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public static function set($key,$value){
self::$obj->$key = $value;
}
public static function get($key){
return self::$obj->$key;
}
}
?>
And i use the following to set my variable into an object of my static class :
<?php
include 'cache.php';
$cache = new Cache();
$cache->set("foo", "bar");
?>
And this is retrieve the variable
<?php
include 'cache.php';
$cache = new Cache();
$echo = $cache->get("foo");
echo $echo //doesn't echo anything
?>
What am i doing wrong ? Thank you

I've adapted #prodigitalson's code above to get something rudimentary that works (and has much room for improvement):
class VarCache {
protected static $instance;
protected static $data = array();
protected function __construct() {}
public static function getInstance() {
if(!self::$instance) {
self:$instance = new self();
}
return self::$instance;
}
public function get($key) {
self::getInstance();
return isset(self::$data[$key]) ? self::$data[$key] : null;
}
public function set($key, $value) {
self::getInstance();
self::$data[$key] = $value;
}
}
Usage
VarCache::set('foo', 'bar');
echo VarCache::get('foo');
// 'bar'
You'll want this class to be available everywhere you need it, and if you want it to persist between requests, I'd consider using Memcached or something similar, which will give you everything you need.
You could alternatively use some SPL functions, like ArrayObject, if you wanted to be clever :)

Try this:
class VarCache {
protected $instance;
protected $data = array();
protected __construct() {}
public static function getInstance()
{
if(!self::$instance) {
self:$instance = new self();
}
return self::$instance;
}
public function __get($key) {
return isset($this->data[$key]) ? $this->data[$key] : null;
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
}
// usage
VarCache::getInstance()->theKey = 'somevalue';
echo VarCache::getInstance()->theKey;

Related

PHP simple chain class methods without create object

in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}

Calling inherited method form base class

I have an extended class with an overriden method doSomething().
For some reason the inherited class' method never runs only the base one.
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
result:
do something
do something
The second one should be "do something differently" at least that's what I'm expecting.
Can anyone tell me what I'm doing wrong? Thanks
In this case, you need using late static binding (5.3+). Change in parent method getInstance line :
$instance = new cDemoClass();
to
$instance = new static();
You will get:
do something
do something differently
Read more about this feature here: http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Because cDemoClassEx::getInstance(); is still returning new cDemoClass();. You have to also overwrite the getInstance() method:
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClassEx();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
You have to override with the cDemoClassEx::getInstance() and change this line
$instance = new cDemoClass();
into
$instance = new cDemoClassEx();
You will also need to declare the cDemoClass::__construct() as protected or simply override it in cDemoClassEx.

Singleton initialization configuration

There is a public library, and there is a class that can have only one instance in one PHP process, so it's Singleton. The problem is that initialization of this class require some configuration arguments and I can't find good issue to pass them in class constructor.
The only issue I found is:
public static function init($params) {
if(self::$instance) {
throw new Exception(__CLASS__ . ' already initialized');
}
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance() {
if(!self::$instance) {
throw new Exception(__CLASS__ . ' is not initialized');
}
return self::$instance;
}
But I don't think that it's so really good.Is there any other ideas?
Thanks!
There is example of bad, but working issue:
if(!defined('PSEOUDSINGLETON_PARAM')) {
define('PSEOUDSINGLETON_PARAM', 'default value');
}
class PseoudoSingleton {
protected function __construct($param1 = PSEOUDSINGLETON_PARAM) {
// ...
}
public static function getInstance() {
if(!self::$instance) {
$class = __CLASS__;
self::$instance = new $class();
}
return self::$instance;
}
}
/* on library/utility level */
class nonSingletonService { public function __construct($options){} }
/* on application logic level, so, knows all context */
function getSingleton(){
static $inst;
if (!$inst) $inst=new nonSingletonService(calculateParameters());
return $inst;
}
Sample Singleton implementation:
class MySingleton
{
private static $_INSTANCE = null;
private function __construct()
{
// put initialization code here
}
public static function getInstance()
{
if(self::$_INSTANCE === null) self::$_INSTANCE = new MySingleton();
return self::$_INSTANCE;
}
}
Note that constructor is private, so it can only be called from the class itself.
References to the instance can be only obtained by getInstance call, which creates the object on first call, any subsequent calls will return references to an existing object.
Why are you checking it twice?
Just do the following:
private static function init($params) {
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance($params) {
if(!self::$instance) {
self::init($params);
}
return self::$instance;
}
That way, you know that you only need to check once and you know you only call init() if the instance is not initialized.

Creating a static array without changing thousands of lines of code

We have a class that holds a public array called $saved that contains lots of data required to share between methods (example below)...
class Common {
public $saved = array();
public function setUser($data) {
$this->saved['user_data'] = $data;
}
public function getUserID() {
return $this->saved['user_data']['id'];
}
}
There are literally thousands of lines of code that work like this.
The problem is that new instance of classes that extend Common are being made within some methods so when they access $saved it does not hold the same data.
The solution is to make $saved a static variable, however I can't change all of the references to $this->saved so I want to try and keep the code identical but make it act static.
Here is my attempt to make $this->saved calls static...
class PropertyTest {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
class Common {
public $saved;
private static $_instance;
public function __construct() {
$this->saved = self::getInstance();
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new PropertyTest();
self::$_instance->foo = array();
}
return self::$_instance->foo;
}
}
This doesn't quite work when setting a variable it doesn't seem to stay static (test case below)...
class Template extends Common {
public function __construct() {
parent::__construct();
$this->saved['user_data'] = array('name' => 'bob');
$user = new User();
}
}
class User extends Common {
public function __construct() {
parent::__construct();
$this->saved['user_data']['name'] .= " rocks!";
$this->saved['user_data']['id'] = array(400, 10, 20);
}
}
$tpl = new Template();
print_r($tpl->saved['user_data']);
$this->saved is empty when User gets initialized and doesn't seem to be the same variable, the final print_r only shows an array of name => bob.
Any ideas?
First of all, I have to say that, IMO, it is not that good to use an instance's property as a class's property ($saved is not declared as static but its value is shared with all instance).
Here is a working version http://codepad.org/8hj1MOCT, and here is the commented code. Basically, the trick is located in using both ArrayAccess interface and the singleton pattern.
class Accumulator implements ArrayAccess {
private $container = array();
private static $instance = null;
private function __construct() {
}
public function getInstance() {
if( self::$instance === null ) {
self::$instance = new self();
}
return self::$instance;
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
class Common {
public $saved = null;
public function __construct() {
// initialize the "saved" object's property with the singleton
// that variable can be used with the array syntax thanks to the ArrayAccess interface
// so you won't have to modify your actual code
// but also, since it's an object, this local "$this->saved" is a reference to the singleton object
// so any change made to "$this->saved" is in reality made into the Accumulator::$instance variable
$this->saved = Accumulator::getInstance();
}
public function setUser($data) {
$this->saved['user_data'] = $data;
}
public function getUser() {
return $this->saved['user_data'];
}
}
class Template extends Common {
// you can redeclare the variable or not. Since the property is inherited, IMO you should not redeclare it, but it works in both cases
// public $saved = null;
public function __construct() {
// maybe we can move this initialization in a method in the parent class and call that method here
$this->saved = Accumulator::getInstance();
}
}
I think there are a number of issues with this implementation that could well come back to bite you. However, in your current implementation your contructing a new instance (albeit through a static call) every time.
Instead use getInstance() as your singleton hook, and make your __construct private, as you'll only be accessing it from with the context of the Common class.
Like so:
class Common {
public $saved;
private static $_instance;
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self();
... any other modifications you want to make ....
}
return self::$_instance;
}
}
And don't ever run parent::_construct(), instead always use the getInstance() method.
You might also want to ditch the idea of extending this singleton class. This is really a bad antipattern and could cost you a number of issues in the long run. Instead just maintain a Common class that other classes can read / write to. As its a singleton you don't need to worry about injection.
I seem to have solved the problem, by making $this->saved a reference to a static variable it works...
class Common {
private static $savedData = array();
public $saved;
public function __construct() {
$this->saved =& self::$savedData;
}
}

PHP Error: Fatal error: Using $this when not in object context

public static function assign($name, $value)
{
$this->params[] = array($name => $value);
}
public static function draw()
{
return $this->params;
}
}
<?php
$test = Templater::assign('key', 'value')->draw();
print_r($test);
I need to function "assign" was static, but $params was common for the whole class..
But this code is not working.
Fatal error: Using $this when not in object context
Any ideas?
It sounds like you want $params to be static:
<?php
class Templater
{
static $params = array();
public static function assign($name, $value)
{
self::$params[] = array($name => $value);
}
public static function draw()
{
return self::$params;
}
}
<?php
Templater::assign('key', 'value');
$test = Templater::draw();
print_r($test);
$this keyword refers to the class instance. When you are trying to call it inside a static method no class instance is used. So your assign method cannot be static to interact with $params, that is not static. Make $params static, or assign dynamic (not static).
<?php
class Templater
{
static var $params = array();
public static function assign($name, $value)
{
$this->params[] = array($name => $value);
}
public static dunction draw()
{
return self::params;
}
}
or:
<?php
class Templater
{
var $params = array();
public function assign($name, $value)
{
$this->params[] = array($name => $value);
}
public dunction draw()
{
return $this->params;
}
}
Both will work, but you must to choose the one that is more adequate for your application's design.
Singleton would work nice here
class Templater {
private static $instance = null;
private $params = array();
public function __construct(){
return $this;
}
public static function instance(){
if(is_null(self::$instance)) self::$instance = new self();
return self::$instance;
}
public function assign($name, $value){
$this->params[$name] = $value;
return $this;
}
public function draw(){
return $this->params;
}
}
Usage:
$test = Templater::instance()
->assign('var1', 'value1')
->assign('var2', 'value2')
->draw();
print_r($test);
If you mean $params to be a static field, use:
class Templater {
private static $params = array();
public static function assign($name, $value) {
self::params[] = array($name => $value);
}
public static dunction draw() {
return self::params;
}
}
static functions have no $this context.
By the way, don't use var for declaring instance variables. That's PHP4. Do it the PHP5 way.

Categories