Skip to content
Permalink
Browse files

Optimizing Entities accessors by caching the result in another array.

This also helps users doing lazy loading of associations so they don't
have to store a flag for whether the association was tried to be loaded
before or not.
  • Loading branch information...
lorenzo committed May 7, 2015
1 parent 2b21a8d commit a062b538520f94354a3998d3542539590b4912fc
Showing with 35 additions and 2 deletions.
  1. +13 −0 src/Datasource/EntityTrait.php
  2. +22 −2 tests/TestCase/ORM/EntityTest.php
@@ -115,6 +115,13 @@ trait EntityTrait
*/
protected $_registryAlias;
/**
* Holds a list of properties that were mutaded using the get accessor
*
* @var array
*/
protected $_mutated = [];
/**
* Magic getter to access properties that have been set in this entity
*
@@ -235,6 +242,7 @@ public function set($property, $value = null, array $options = [])
continue;
}
unset($this->_mutated[$p]);
$this->dirty($p, true);
if (!isset($this->_original[$p]) &&
@@ -271,6 +279,10 @@ public function &get($property)
throw new InvalidArgumentException('Cannot get an empty property');
}
if (array_key_exists($property, $this->_mutated)) {
return $this->_mutated[$property];
}
$value = null;
$method = '_get' . Inflector::camelize($property);
@@ -280,6 +292,7 @@ public function &get($property)
if ($this->_methodExists($method)) {
$result = $this->{$method}($value);
$this->_mutated[$property] = $result;
return $result;
}
return $value;
@@ -227,17 +227,37 @@ public function testGetNoGetters()
public function testGetCustomGetters()
{
$entity = $this->getMock('\Cake\ORM\Entity', ['_getName']);
$entity->expects($this->exactly(2))->method('_getName')
$entity->expects($this->once())->method('_getName')
->with('Jones')
->will($this->returnCallback(function ($name) {
$this->assertSame('Jones', $name);
return 'Dr. ' . $name;
}));
$entity->set('name', 'Jones');
$this->assertEquals('Dr. Jones', $entity->get('name'));
$this->assertEquals('Dr. Jones', $entity->get('name'));
}
/**
* Tests get with custom getter
*
* @return void
*/
public function testGetCustomGettersAfterSet()
{
$entity = $this->getMock('\Cake\ORM\Entity', ['_getName']);
$entity->expects($this->exactly(2))->method('_getName')
->will($this->returnCallback(function ($name) {
return 'Dr. ' . $name;
}));
$entity->set('name', 'Jones');
$this->assertEquals('Dr. Jones', $entity->get('name'));
$this->assertEquals('Dr. Jones', $entity->get('name'));
$entity->set('name', 'Mark');
$this->assertEquals('Dr. Mark', $entity->get('name'));
$this->assertEquals('Dr. Mark', $entity->get('name'));
}
/**
* Test magic property setting with no custom setter
*

0 comments on commit a062b53

Please sign in to comment.
You can’t perform that action at this time.