From f8e3b4b035bc9d99f09dc57ca9789bcc7ee80ea2 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 27 Jan 2010 11:10:45 +0100 Subject: [PATCH] [DependencyInjection] added a __call() method to Container to allow usage of getXXXService() methods even whithout a PHP dump (allows for faster production environments) --- .../DependencyInjection/Container.php | 18 ++++++++++++++++++ .../DependencyInjection/ContainerTest.php | 18 +++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Components/DependencyInjection/Container.php b/src/Symfony/Components/DependencyInjection/Container.php index ef003acef83c..30213fceb698 100644 --- a/src/Symfony/Components/DependencyInjection/Container.php +++ b/src/Symfony/Components/DependencyInjection/Container.php @@ -375,6 +375,24 @@ public function valid() return $this->count > 0; } + /** + * Catches unknown methods. + * + * @param string $method The called method name + * @param array $arguments The method arguments + * + * @return mixed + */ + public function __call($method, $arguments) + { + if (!preg_match('/^get(.+)Service$/', $method, $match)) + { + throw new \RuntimeException(sprintf('Call to undefined method %s::%s.', get_class($this), $method)); + } + + return $this->getService(self::underscore($match[1])); + } + static public function camelize($id) { return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $id); diff --git a/tests/unit/Symfony/Components/DependencyInjection/ContainerTest.php b/tests/unit/Symfony/Components/DependencyInjection/ContainerTest.php index 00eaa1a9a69b..b4033c907a73 100644 --- a/tests/unit/Symfony/Components/DependencyInjection/ContainerTest.php +++ b/tests/unit/Symfony/Components/DependencyInjection/ContainerTest.php @@ -14,7 +14,7 @@ $fixturesPath = __DIR__.'/../../../../fixtures/Symfony/Components/DependencyInjection/'; -$t = new LimeTest(41); +$t = new LimeTest(43); // __construct() $t->diag('__construct()'); @@ -206,3 +206,19 @@ protected function getFoo_BazService() 'foo.baz' => spl_object_hash($sc->__foo_baz), 'foo' => spl_object_hash($foo)), 'Container implements the Iterator interface'); + +// __call() +$t->diag('__call()'); +$sc = new Container(); +$sc->setService('foo_bar.foo', $foo = new stdClass()); +$t->is($sc->getFooBar_FooService(), $foo, '__call() finds services is the method is getXXXService()'); + +try +{ + $sc->getFooBar_Foo(); + $t->pass('__call() throws a \RuntimeException exception if the method is not a service method'); +} +catch (\RuntimeException $e) +{ + $t->pass('__call() throws a \RuntimeException exception if the method is not a service method'); +}