<?php
/**
* This is a proxy class of entity object, it will be used for the lazyload in the X-to-X relations
* The real entity object will be instanced when the user call the corresponding property.
* Be careful about the array, anEntityProxy->arrayProperty[] = $newElement dont work.
* The user should define the array insert operation as a function, like: anEntityProxy->addItem($newElement)
*
* @package com.freeorm
* @author Yide Zou
* @link http://www.freeorm.com
* @copyright Copyright (c) 2010 Yide Zou <hide@address.com>.
* All Rights Reserved.
* @license This software is released under the terms of the GNU Lesser General Public License
* A copy of which is available from http://www.gnu.org/copyleft/lesser.html
*/
class EntityProxy
{
// the class name of the linked entity
public $classname;
// the id of the linked entity
public $id;
// true if $instance !== null
public $loaded = false;
// the session object
private $session;
// the instance of the proxied object
private $instance = null;
public function __construct(Session $session, $classname, $id)
{
$this->session = $session;
$this->classname = $classname;
$this->id = $id;
}
/**
* Lazy load
*/
private function createInstance()
{
if ($this->instance === null)
{
$this->instance = $this->session->get($this->classname, $this->id);
$this->loaded = true;
}
}
/**
* The compare two Entity, if they are both EntityProxy then just compare classname and id
* if the $obj is a real object, then compare its class and id
* @param $obj
* @return true if they are same
*/
public function equals($obj)
{
if ($obj === null)
return false;
if ($obj instanceof EntityProxy)
return ($this->classname == $obj->classname) &&
($this->id == $obj->id);
else
{
return ($this->classname == get_class($obj)) &&
($this->id == $this->session->getObjId($obj));
}
}
/**
* Compare two unloaded EntityProxy, in order to prevent the useless database hit during dirtycheck
* @param $objcache
* @param $objwatcher
* @return true if the both EntityProxy still not be loaded and with the same classname and id, that means they are real same
*/
public function equalsAndUnloaded(EntityProxy $obj)
{
if ($this->loaded || $obj->loaded)
return false;
return $this->equals($obj);
}
/*
* Proxy functions
*/
public function __get($name)
{
$this->createInstance();
return $this->instance->$name;
}
public function __set($name, $value)
{
$this->createInstance();
$this->instance->$name = $value;
}
public function __call($name, $arguments)
{
$this->createInstance();
return call_user_func_array(array($this->instance, $name), $arguments);
}
public function __callStatic($name, $arguments)
{
$this->createInstance();
return call_user_func_array(array($this->classname, $name), $arguments);
}
}