ID:          29995
 Updated by:  [EMAIL PROTECTED]
 Reported By: tuxie at dekadance dot se
-Status:      Open
+Status:      Bogus
 Bug Type:    Feature/Change Request
 PHP Version: 5.0.1
 New Comment:

Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions. 

Thank you for your interest in PHP.

Use a Factory


Previous Comments:
------------------------------------------------------------------------

[2004-09-06 09:54:14] tuxie at dekadance dot se

Description:
------------
I make extensive use of Memcache in my application.
A simplified version of many classes I have:

class Test
{
  private $id;
  private $data = array();
  private $cachekey;

  public function __construct($id)
  {
    global $cache;

    $this->id = $id;
    $this->cachekey = 'Test:'. $id;
    $this->data = /* Fill it from the database */;

    // Cache myself:
    $cache->set($this->cacheid, $this, 0, 0);
  }

  public function __get($var)
  {
    return $this->data[$var]:
  }

  public function __set($var,$val)
  {
    global $cache;

    if( $this->data[$var] == $val) return;

    /* update database here*/

    // Update myself in the cache:
    $this->data[$var] = $val;
    $cache->set($this->cachekey, $this, 0, 0);
  }
}


On every page I want to use the object I now have to do:

if( false === $testObj = $cache->get('Test:'.$id) )
{
  $testObj = new Test($id);
}


Now here is my feature request:
If I could assign $this in the constructor my code would be much more
readable and the caching details would be completly transparent to the
user of the class. Then the constructor could look like this:

  public function __construct($id)
  {
    global $cache;

    if( $cachedObj = $cache->get('Test:'.$id) )
      $this = &$cachedObj;
    else {
      $this->id = $id;
      $this->cachekey = 'Test:'. $id;
      $this->data = /* Fill it from the database */;

      // Cache myself:
      $cache->set($this->cacheid, $this, 0, 0);
    }
  }

Using the class would now be simple and standard:
$testObj = new Test($id);




------------------------------------------------------------------------


-- 
Edit this bug report at http://bugs.php.net/?id=29995&edit=1

Reply via email to