diff options
author | Matthieu Napoli <matthieu@mnapoli.fr> | 2015-03-17 06:14:11 +0300 |
---|---|---|
committer | Matthieu Napoli <matthieu@mnapoli.fr> | 2015-03-17 06:14:11 +0300 |
commit | f76ec2495b19c8b33b8f74f6e3e7e8d9be45324a (patch) | |
tree | fa2483f6b20a43d3adb3beec18e44546ed16ada5 /core | |
parent | 42807de32ab64bef2c18eb1f6a6d0a0358f8c57f (diff) | |
parent | 3dabc9e1729b0c64240545b22387c4d36c9fbf3c (diff) |
Merge pull request #7407 from piwik/di-api
Dependency injection in API classes
Diffstat (limited to 'core')
-rw-r--r-- | core/Plugin/API.php | 58 |
1 files changed, 55 insertions, 3 deletions
diff --git a/core/Plugin/API.php b/core/Plugin/API.php index 4e5095a3aa..40bd334f95 100644 --- a/core/Plugin/API.php +++ b/core/Plugin/API.php @@ -9,7 +9,8 @@ namespace Piwik\Plugin; -use Piwik\Singleton; +use Piwik\Container\StaticContainer; +use Psr\Log\LoggerInterface; /** * The base class of all API singletons. @@ -39,7 +40,58 @@ use Piwik\Singleton; * * @api */ -abstract class API extends Singleton +abstract class API { - + private static $instances; + + /** + * Returns the singleton instance for the derived class. If the singleton instance + * has not been created, this method will create it. + * + * @return static + */ + public static function getInstance() { + $class = get_called_class(); + + if (!isset(self::$instances[$class])) { + $container = StaticContainer::getContainer(); + + $refl = new \ReflectionClass($class); + + if (!$refl->getConstructor() || $refl->getConstructor()->isPublic()) { + self::$instances[$class] = $container->get($class); + } else { + /** @var LoggerInterface $logger */ + $logger = $container->get('Psr\Log\LoggerInterface'); + + // BC with API defining a protected constructor + $logger->notice('The API class {class} defines a protected constructor which is deprecated, make the constructor public instead', array('class' => $class)); + self::$instances[$class] = new $class; + } + } + + return self::$instances[$class]; + } + + /** + * Used in tests only + * @ignore + * @deprecated + */ + public static function unsetInstance() + { + $class = get_called_class(); + unset(self::$instances[$class]); + } + + /** + * Sets the singleton instance. For testing purposes. + * @ignore + * @deprecated + */ + public static function setSingletonInstance($instance) + { + $class = get_called_class(); + self::$instances[$class] = $instance; + } } |