Browse files

We now store objects on a per-parameter basis, so that getObj(1) and

getObj(2) ALWAYS return the object for that parameter (which wasn't the
case before).
  • Loading branch information...
1 parent bcf52b8 commit 00e8a37530932b26f1f8d45ccc8ccc8d36954a69 @inxilpro committed Jan 11, 2012
Showing with 39 additions and 3 deletions.
  1. +28 −3 lib/Zit/Container.php
  2. +11 −0 tests/ContainerTests.php
View
31 lib/Zit/Container.php
@@ -53,7 +53,17 @@ public function get($name)
{
// Return object if it's already instantiated
if (isset($this->_objects[$name])) {
- return $this->_objects[$name];
+ $args = func_get_args();
+ array_shift($args);
+
+ $key = $this->_keyForArguments($args);
+ if ('_no_arguments' == $key && !isset($this->_objects[$name][$key]) && !empty($this->_objects[$name])) {
+ $key = key($this->_objects[$name]);
+ }
+
+ if (isset($this->_objects[$name][$key])) {
+ return $this->_objects[$name][$key];
+ }
}
// Otherwise create a new one
@@ -68,19 +78,34 @@ public function fresh($name)
$arguments = func_get_args();
$arguments[0] = $this;
- $this->_objects[$name] = call_user_func_array($this->_callbacks[$name], $arguments);
- return $this->_objects[$name];
+ $key = $this->_keyForArguments($arguments);
+ $this->_objects[$name][$key] = call_user_func_array($this->_callbacks[$name], $arguments);
+ return $this->_objects[$name][$key];
}
public function delete($name)
{
+ // TODO: Should this also delete the callback?
if (isset($this->_objects[$name])) {
unset($this->_objects[$name]);
return true;
}
return false;
}
+
+ protected function _keyForArguments(Array $arguments)
+ {
+ if (count($arguments) && $this === $arguments[0]) {
+ array_shift($arguments);
+ }
+
+ if (0 == count($arguments)) {
+ return '_no_arguments';
+ }
+
+ return md5(serialize($arguments));
+ }
}
View
11 tests/ContainerTests.php
@@ -109,6 +109,15 @@ public function testFresh()
$this->assertNotSame($o4, $o5);
}
+ /*
+ public function testDelete()
+ {
+ $c = $this->container;
+ $c->setObj(function() { return new \stdClass(); });
+ $c->deleteObj();
+ }
+ */
+
public function testDependency()
{
$c = $this->container;
@@ -140,10 +149,12 @@ public function testConstructorArguments()
$o1 = $c->getTestObj('A');
$o2 = $c->getTestObj();
$o3 = $c->newTestObj('B');
+ $o4 = $c->getTestObj('A');
$this->assertAttributeEquals('A', 'name', $o1);
$this->assertAttributeEquals('A', 'name', $o2);
$this->assertAttributeEquals('B', 'name', $o3);
+ $this->assertSame($o1, $o4);
}
public function testAlternateMethodFormat()

0 comments on commit 00e8a37

Please sign in to comment.