summaryrefslogtreecommitdiffstats
path: root/lib/private/appframework
diff options
context:
space:
mode:
authorBernhard Posselt <dev@bernhard-posselt.com>2014-12-13 19:28:20 +0100
committerMorris Jobke <hey@morrisjobke.de>2014-12-23 09:50:42 +0100
commitf1951237653ffbbf7fd75f815f401783658cec5e (patch)
tree360c85776f363e4b4447272c96c06d25863138d1 /lib/private/appframework
parentd8f04f5a97e77bf5fb84b05ddd9b3a476fecfb7c (diff)
downloadnextcloud-server-f1951237653ffbbf7fd75f815f401783658cec5e.tar.gz
nextcloud-server-f1951237653ffbbf7fd75f815f401783658cec5e.zip
Intelligent container
* resolves dependencies by type hint or variable name * simpler route.php * implementation of https://github.com/owncloud/core/issues/12829 Generates and injects parameters automatically. You can now build full classes like $c->query('MyClassName') without having to register it as a service. The resolved object's instance will be saved by using registerService. If a constructor parameter is not type hinted, the parameter name will be taken. Therefore the following two implementations are identical: class Class1 { function __construct(MyClassName $class) class Class1 { function __construct($MyClassName) This makes it possible to also inject primitive values such as strings, arrays etc. In addition if the query could not be resolved, a `QueryException` is now thrown Routes can now be returned as an array from `routes.php` and an `appinfo/application.php` is optional Old commit messages: make it possible to return the routes instead of having to intialize the application try to get the controller by convention add first implementation of automatic resolve add another test just to be sure store the resolved object more tests add phpdoc to public app.php method use the same variable for the public app.php method deprecate old methods and add services for public interfaces deprecated getServer method disallow private api injection for apps other than core or settings (settings should be an app goddamnit :D) register userid because its such an often used variable fix indention and leading slash use test namespace add deprecation reasons, remove private api usage checks and remove deprecation from getServer() add additional public interfaces add public interface for rootfolder fix syntax error remove deprecation from methods where no alternative is there yet remove deprecated from method which has no alternative add timezone public service for #12881 add another deprecation hint move deprecation into separate branch remove dead comment first try to get the namespace from the info.xml, if it does not exist, just uppercase the first letter also trim the namespace name add an interface for timefactory move timefactory to public and add icontrollermethodreflector keep core interface fix copyright date in headers
Diffstat (limited to 'lib/private/appframework')
-rw-r--r--lib/private/appframework/app.php44
-rw-r--r--lib/private/appframework/dependencyinjection/dicontainer.php177
-rw-r--r--lib/private/appframework/utility/simplecontainer.php85
3 files changed, 296 insertions, 10 deletions
diff --git a/lib/private/appframework/app.php b/lib/private/appframework/app.php
index f56ba4af870..b94c7bd9957 100644
--- a/lib/private/appframework/app.php
+++ b/lib/private/appframework/app.php
@@ -24,8 +24,9 @@
namespace OC\AppFramework;
-use OC\AppFramework\DependencyInjection\DIContainer;
-
+use \OC_App;
+use \OC\AppFramework\DependencyInjection\DIContainer;
+use \OCP\AppFramework\QueryException;
/**
* Entry point for every request in your app. You can consider this as your
@@ -37,6 +38,34 @@ class App {
/**
+ * Turns an app id into a namespace by either reading the appinfo.xml's
+ * namespace tag or uppercasing the appid's first letter
+ * @param string $appId the app id
+ * @param string $topNamespace the namespace which should be prepended to
+ * the transformed app id, defaults to OCA\
+ * @return string the starting namespace for the app
+ */
+ public static function buildAppNamespace($appId, $topNamespace='OCA\\') {
+ // first try to parse the app's appinfo/info.xml <namespace> tag
+ $filePath = OC_App::getAppPath($appId) . '/appinfo/info.xml';
+ $loadEntities = libxml_disable_entity_loader(false);
+ $xml = @simplexml_load_file($filePath);
+ libxml_disable_entity_loader($loadEntities);
+
+ if ($xml) {
+ $result = $xml->xpath('/info/namespace');
+ if ($result && count($result) > 0) {
+ // take first namespace result
+ return $topNamespace . trim((string) $result[0]);
+ }
+ }
+
+ // if the tag is not found, fall back to uppercasing the first letter
+ return $topNamespace . ucfirst($appId);
+ }
+
+
+ /**
* Shortcut for calling a controller method and printing the result
* @param string $controllerName the name of the controller under which it is
* stored in the DI container
@@ -48,7 +77,16 @@ class App {
if (!is_null($urlParams)) {
$container['urlParams'] = $urlParams;
}
- $controller = $container[$controllerName];
+ $appName = $container['AppName'];
+
+ // first try $controllerName then go for \OCA\AppName\Controller\$controllerName
+ try {
+ $controller = $container->query($controllerName);
+ } catch(QueryException $e) {
+ $appNameSpace = self::buildAppNamespace($appName);
+ $controllerName = $appNameSpace . '\\Controller\\' . $controllerName;
+ $controller = $container->query($controllerName);
+ }
// initialize the dispatcher and run all the middleware before the controller
$dispatcher = $container['Dispatcher'];
diff --git a/lib/private/appframework/dependencyinjection/dicontainer.php b/lib/private/appframework/dependencyinjection/dicontainer.php
index dc57ef4c167..2c5089865a3 100644
--- a/lib/private/appframework/dependencyinjection/dicontainer.php
+++ b/lib/private/appframework/dependencyinjection/dicontainer.php
@@ -36,12 +36,13 @@ use OC\AppFramework\Utility\SimpleContainer;
use OC\AppFramework\Utility\TimeFactory;
use OC\AppFramework\Utility\ControllerMethodReflector;
use OCP\AppFramework\IApi;
+use OCP\AppFramework\QueryException;
use OCP\AppFramework\IAppContainer;
use OCP\AppFramework\Middleware;
use OCP\IServerContainer;
-class DIContainer extends SimpleContainer implements IAppContainer{
+class DIContainer extends SimpleContainer implements IAppContainer {
/**
* @var array
@@ -53,19 +54,181 @@ class DIContainer extends SimpleContainer implements IAppContainer{
* @param string $appName the name of the app
*/
public function __construct($appName, $urlParams = array()){
-
$this['AppName'] = $appName;
$this['urlParams'] = $urlParams;
- $this->registerParameter('ServerContainer', \OC::$server);
+ /**
+ * Core services
+ */
+ $this->registerService('OCP\\IAppConfig', function($c) {
+ return \OC::$server->getAppConfig();
+ });
- $this->registerService('API', function($c){
- return new API($c['AppName']);
+ $this->registerService('OCP\\IAppManager', function($c) {
+ return \OC::$server->getAppManager();
+ });
+
+ $this->registerService('OCP\\IAvatarManager', function($c) {
+ return \OC::$server->getAvatarManager();
+ });
+
+ $this->registerService('OCP\\Activity\\IManager', function($c) {
+ return \OC::$server->getActivityManager();
+ });
+
+ $this->registerService('OCP\\ICache', function($c) {
+ return \OC::$server->getCache();
+ });
+
+ $this->registerService('OCP\\ICacheFactory', function($c) {
+ return \OC::$server->getMemCacheFactory();
+ });
+
+ $this->registerService('OCP\\IConfig', function($c) {
+ return \OC::$server->getConfig();
+ });
+
+ $this->registerService('OCP\\Contacts\\IManager', function($c) {
+ return \OC::$server->getContactsManager();
+ });
+
+ $this->registerService('OCP\\IDateTimeZone', function($c) {
+ return \OC::$server->getDateTimeZone();
+ });
+
+ $this->registerService('OCP\\IDb', function($c) {
+ return \OC::$server->getDb();
+ });
+
+ $this->registerService('OCP\\IDBConnection', function($c) {
+ return \OC::$server->getDatabaseConnection();
+ });
+
+ $this->registerService('OCP\\Diagnostics\\IEventLogger', function($c) {
+ return \OC::$server->getEventLogger();
+ });
+
+ $this->registerService('OCP\\Diagnostics\\IQueryLogger', function($c) {
+ return \OC::$server->getQueryLogger();
+ });
+
+ $this->registerService('OCP\\Files\\Config\\IMountProviderCollection', function($c) {
+ return \OC::$server->getMountProviderCollection();
+ });
+
+ $this->registerService('OCP\\Files\\IRootFolder', function($c) {
+ return \OC::$server->getRootFolder();
+ });
+
+ $this->registerService('OCP\\IGroupManager', function($c) {
+ return \OC::$server->getGroupManager();
+ });
+
+ $this->registerService('OCP\\IL10N', function($c) {
+ return \OC::$server->getL10N($c->query('AppName'));
+ });
+
+ $this->registerService('OCP\\ILogger', function($c) {
+ return \OC::$server->getLogger();
+ });
+
+ $this->registerService('OCP\\BackgroundJob\\IJobList', function($c) {
+ return \OC::$server->getJobList();
+ });
+
+ $this->registerService('OCP\\AppFramework\\Utility\\IControllerMethodReflector', function($c) {
+ return $c->query('ControllerMethodReflector');
+ });
+
+ $this->registerService('OCP\\INavigationManager', function($c) {
+ return \OC::$server->getNavigationManager();
});
+ $this->registerService('OCP\\IPreview', function($c) {
+ return \OC::$server->getPreviewManager();
+ });
+
+ $this->registerService('OCP\\IRequest', function($c) {
+ return $c->query('Request');
+ });
+
+ $this->registerService('OCP\\ITagManager', function($c) {
+ return \OC::$server->getTagManager();
+ });
+
+ $this->registerService('OCP\\ITempManager', function($c) {
+ return \OC::$server->getTempManager();
+ });
+
+ $this->registerService('OCP\\AppFramework\\Utility\\ITimeFactory', function($c) {
+ return $c->query('TimeFactory');
+ });
+
+ $this->registerService('OCP\\Route\\IRouter', function($c) {
+ return \OC::$server->getRouter();
+ });
+
+ $this->registerService('OCP\\ISearch', function($c) {
+ return \OC::$server->getSearch();
+ });
+
+ $this->registerService('OCP\\ISearch', function($c) {
+ return \OC::$server->getSearch();
+ });
+
+ $this->registerService('OCP\\Security\\ICrypto', function($c) {
+ return \OC::$server->getCrypto();
+ });
+
+ $this->registerService('OCP\\Security\\IHasher', function($c) {
+ return \OC::$server->getHasher();
+ });
+
+ $this->registerService('OCP\\Security\\ISecureRandom', function($c) {
+ return \OC::$server->getSecureRandom();
+ });
+
+ $this->registerService('OCP\\IURLGenerator', function($c) {
+ return \OC::$server->getURLGenerator();
+ });
+
+ $this->registerService('OCP\\IUserManager', function($c) {
+ return \OC::$server->getUserManager();
+ });
+
+ $this->registerService('OCP\\IUserSession', function($c) {
+ return \OC::$server->getUserSession();
+ });
+
+ $this->registerService('ServerContainer', function ($c) {
+ $c->query('OCP\\ILogger')->warning(
+ 'Accessing the server container is deprecated. Use type ' .
+ 'annotations to inject core services instead!'
+ );
+ return \OC::$server;
+ });
+
+ // commonly used attributes
+ $this->registerService('UserId', function ($c) {
+ return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
+ });
+
+ $this->registerService('WebRoot', function ($c) {
+ return $c->query('ServerContainer')->getWebRoot();
+ });
+
+
/**
- * Http
+ * App Framework APIs
*/
+ $this->registerService('API', function($c){
+ $c->query('OCP\\ILogger')->warning(
+ 'Accessing the API class is deprecated! Use the appropriate ' .
+ 'services instead!'
+ );
+ return new API($c['AppName']);
+ });
+
$this->registerService('Request', function($c) {
/** @var $c SimpleContainer */
/** @var $server SimpleContainer */
@@ -234,4 +397,6 @@ class DIContainer extends SimpleContainer implements IAppContainer{
}
\OCP\Util::writeLog($this->getAppName(), $message, $level);
}
+
+
}
diff --git a/lib/private/appframework/utility/simplecontainer.php b/lib/private/appframework/utility/simplecontainer.php
index 55b9cf7a977..68d52d759e0 100644
--- a/lib/private/appframework/utility/simplecontainer.php
+++ b/lib/private/appframework/utility/simplecontainer.php
@@ -1,7 +1,29 @@
<?php
+/**
+ * ownCloud - App Framework
+ *
+ * @author Bernhard Posselt
+ * @copyright 2014 Bernhard Posselt <dev@bernhard-posselt.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this library. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
namespace OC\AppFramework\Utility;
+use \OCP\AppFramework\QueryException;
+
/**
* Class SimpleContainer
*
@@ -9,12 +31,71 @@ namespace OC\AppFramework\Utility;
*/
class SimpleContainer extends \Pimple\Container implements \OCP\IContainer {
+
+ /**
+ * @param ReflectionClass $class the class to instantiate
+ * @return stdClass the created class
+ */
+ private function buildClass(\ReflectionClass $class) {
+ $constructor = $class->getConstructor();
+ if ($constructor === null) {
+ return $class->newInstance();
+ } else {
+ $parameters = [];
+ foreach ($constructor->getParameters() as $parameter) {
+ $parameterClass = $parameter->getClass();
+
+ // try to find out if it is a class or a simple parameter
+ if ($parameterClass === null) {
+ $resolveName = $parameter->getName();
+ } else {
+ $resolveName = $parameterClass->name;
+ }
+
+ $parameters[] = $this->query($resolveName);
+ }
+ return $class->newInstanceArgs($parameters);
+ }
+ }
+
+
+ /**
+ * If a parameter is not registered in the container try to instantiate it
+ * by using reflection to find out how to build the class
+ * @param string $name the class name to resolve
+ * @throws QueryException if the class could not be found or instantiated
+ */
+ private function resolve($name) {
+ $baseMsg = 'Could not resolve ' . $name . '!';
+ try {
+ $class = new \ReflectionClass($name);
+ if ($class->isInstantiable()) {
+ return $this->buildClass($class);
+ } else {
+ throw new QueryException($baseMsg .
+ ' Class can not be instantiated');
+ }
+ } catch(\ReflectionException $e) {
+ throw new QueryException($baseMsg . ' ' . $e->getMessage());
+ }
+ }
+
+
/**
* @param string $name name of the service to query for
* @return mixed registered service for the given $name
+ * @throws QueryExcpetion if the query could not be resolved
*/
public function query($name) {
- return $this->offsetGet($name);
+ if ($this->offsetExists($name)) {
+ return $this->offsetGet($name);
+ } else {
+ $object = $this->resolve($name);
+ $this->registerService($name, function () use ($object) {
+ return $object;
+ });
+ return $object;
+ }
}
/**
@@ -44,4 +125,6 @@ class SimpleContainer extends \Pimple\Container implements \OCP\IContainer {
$this[$name] = parent::factory($closure);
}
}
+
+
}