Remove DependencyFactory

- Include all necessary classes in `dependencies.config.php`
- Add DI-reference to BaseObject (acts as a global registry)
- Refactor all static "init()" methods to use the global registry

- Refactor Logging for Worker-Logger a little bit
This commit is contained in:
Philipp Holzer 2019-07-21 20:24:16 +02:00
parent 8b344141da
commit 6c2cf494b5
No known key found for this signature in database
GPG key ID: D8365C3D36B77D90
21 changed files with 188 additions and 280 deletions

View file

@ -32,7 +32,6 @@
* *
*/ */
use Friendica\Factory;
use Friendica\Util\ExAuth; use Friendica\Util\ExAuth;
if (sizeof($_SERVER["argv"]) == 0) { if (sizeof($_SERVER["argv"]) == 0) {
@ -54,9 +53,9 @@ require dirname(__DIR__) . '/vendor/autoload.php';
$dice = new \Dice\Dice(); $dice = new \Dice\Dice();
$dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php'); $dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php');
$a = Factory\DependencyFactory::setUp('auth_ejabbered', $dice); $appMode = $dice->create(\Friendica\App\Mode::class);
if ($a->getMode()->isNormal()) { if ($appMode->isNormal()) {
$oAuth = new ExAuth(); $oAuth = new ExAuth();
$oAuth->readStdin(); $oAuth->readStdin();
} }

View file

@ -3,12 +3,9 @@
require dirname(__DIR__) . '/vendor/autoload.php'; require dirname(__DIR__) . '/vendor/autoload.php';
use Friendica\Factory;
$dice = new \Dice\Dice(); $dice = new \Dice\Dice();
$dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php'); $dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php');
$a = Factory\DependencyFactory::setUp('console', $dice); \Friendica\BaseObject::setDependencyInjection($dice);
\Friendica\BaseObject::setApp($a);
(new Friendica\Core\Console($argv))->execute(); (new Friendica\Core\Console($argv))->execute();

View file

@ -11,7 +11,6 @@ use Friendica\Core\Config;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Factory;
// Get options // Get options
$shortopts = 'f'; $shortopts = 'f';
@ -35,7 +34,8 @@ require dirname(__DIR__) . '/vendor/autoload.php';
$dice = new \Dice\Dice(); $dice = new \Dice\Dice();
$dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php'); $dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php');
$a = Factory\DependencyFactory::setUp('daemon', $dice); \Friendica\BaseObject::setDependencyInjection($dice);
$a = \Friendica\BaseObject::getApp();
if ($a->getMode()->isInstall()) { if ($a->getMode()->isInstall()) {
die("Friendica isn't properly installed yet.\n"); die("Friendica isn't properly installed yet.\n");
@ -147,7 +147,7 @@ if (!$foreground) {
file_put_contents($pidfile, $pid); file_put_contents($pidfile, $pid);
// We lose the database connection upon forking // We lose the database connection upon forking
$a->getDatabase()->reconnect(); DBA::reconnect();
} }
Config::set('system', 'worker_daemon_mode', true); Config::set('system', 'worker_daemon_mode', true);

View file

@ -9,7 +9,6 @@ use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Factory;
// Get options // Get options
$shortopts = 'sn'; $shortopts = 'sn';
@ -33,7 +32,8 @@ require dirname(__DIR__) . '/vendor/autoload.php';
$dice = new \Dice\Dice(); $dice = new \Dice\Dice();
$dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php'); $dice = $dice->addRules(include __DIR__ . '/../static/dependencies.config.php');
$a = Factory\DependencyFactory::setUp('worker', $dice); \Friendica\BaseObject::setDependencyInjection($dice);
$a = \Friendica\BaseObject::getApp();
// Check the database structure and possibly fixes it // Check the database structure and possibly fixes it
Update::check($a->getBasePath(), true, $a->getMode()); Update::check($a->getBasePath(), true, $a->getMode());

View file

@ -4,8 +4,6 @@
* Friendica * Friendica
*/ */
use Friendica\Factory;
if (!file_exists(__DIR__ . '/vendor/autoload.php')) { if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
die('Vendor path not found. Please execute "bin/composer.phar --no-dev install" on the command line in the web root.'); die('Vendor path not found. Please execute "bin/composer.phar --no-dev install" on the command line in the web root.');
} }
@ -15,6 +13,8 @@ require __DIR__ . '/vendor/autoload.php';
$dice = new \Dice\Dice(); $dice = new \Dice\Dice();
$dice = $dice->addRules(include __DIR__ . '/static/dependencies.config.php'); $dice = $dice->addRules(include __DIR__ . '/static/dependencies.config.php');
$a = Factory\DependencyFactory::setUp('index', $dice, false); \Friendica\BaseObject::setDependencyInjection($dice);
$a = \Friendica\BaseObject::getApp();
$a->runFrontend(); $a->runFrontend();

View file

@ -378,7 +378,7 @@ function settings_post(App $a)
theme_post($a); theme_post($a);
} }
} else { } else {
$a->getDatabase()->update('user', ['theme' => $theme], ['uid' => local_user()]); DBA::update('user', ['theme' => $theme], ['uid' => local_user()]);
} }
} else { } else {
notice(L10n::t('The theme you chose isn\'t available.')); notice(L10n::t('The theme you chose isn\'t available.'));

View file

@ -197,32 +197,6 @@ class App
return $this->mode; return $this->mode;
} }
/**
* Returns the router of the Application
*
* @return App\Router
*/
public function getRouter()
{
return $this->router;
}
/**
* @return Database
*/
public function getDatabase()
{
return $this->database;
}
/**
* @return L10n
*/
public function getL10n()
{
return $this->l10n;
}
/** /**
* Register a stylesheet file path to be included in the <head> tag of every page. * Register a stylesheet file path to be included in the <head> tag of every page.
* Inclusion is done in App->initHead(). * Inclusion is done in App->initHead().
@ -270,14 +244,11 @@ class App
* @param LoggerInterface $logger The current app logger * @param LoggerInterface $logger The current app logger
* @param Profiler $profiler The profiler of this application * @param Profiler $profiler The profiler of this application
* @param L10n $l10n The translator instance * @param L10n $l10n The translator instance
* @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
* *
* @throws Exception if the Basepath is not usable * @throws Exception if the Basepath is not usable
*/ */
public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, $isBackend = true) public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n)
{ {
BaseObject::setApp($this);
$this->database = $database; $this->database = $database;
$this->config = $config; $this->config = $config;
$this->mode = $mode; $this->mode = $mode;
@ -354,7 +325,7 @@ class App
$this->module = 'home'; $this->module = 'home';
} }
$this->isBackend = $isBackend || $this->checkBackend($this->module); $this->isBackend = $this->isBackend || $this->checkBackend($this->module);
// Detect mobile devices // Detect mobile devices
$mobile_detect = new MobileDetect(); $mobile_detect = new MobileDetect();
@ -375,6 +346,8 @@ class App
*/ */
public function reload() public function reload()
{ {
$this->isBackend = basename($_SERVER['PHP_SELF'], '.php') !== 'index';
$this->getMode()->determine($this->getBasePath()); $this->getMode()->determine($this->getBasePath());
if ($this->getMode()->has(App\Mode::DBAVAILABLE)) { if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {

View file

@ -6,19 +6,32 @@ namespace Friendica;
require_once __DIR__ . '/../boot.php'; require_once __DIR__ . '/../boot.php';
use Dice\Dice;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
/** /**
* Basic object * Basic object
* *
* Contains what is useful to any object * Contains what is useful to any object
*
* Act's like a global registry for classes
*/ */
class BaseObject class BaseObject
{ {
/** /**
* @var App * @var Dice The Dependency Injection library
*/ */
private static $app = null; private static $dice;
/**
* Set's the dependency injection library for a global usage
*
* @param Dice $dice The dependency injection library
*/
public static function setDependencyInjection(Dice $dice)
{
self::$dice = $dice;
}
/** /**
* Get the app * Get the app
@ -26,26 +39,27 @@ class BaseObject
* Same as get_app from boot.php * Same as get_app from boot.php
* *
* @return App * @return App
* @throws \Exception
*/ */
public static function getApp() public static function getApp()
{ {
if (empty(self::$app)) { return self::$dice->create(App::class);
throw new InternalServerErrorException('App isn\'t initialized.');
}
return self::$app;
} }
/** /**
* Set the app * Returns the initialized class based on it's name
* *
* @param App $app App * @param string $name The name of the class
* *
* @return void * @return object The initialized name
*
* @throws InternalServerErrorException
*/ */
public static function setApp(App $app) public static function getClass(string $name)
{ {
self::$app = $app; if (class_exists($name) || interface_exists($name )) {
return self::$dice->create($name);
} else {
throw new InternalServerErrorException('Class \'' . $name . '\' isn\'t valid.');
}
} }
} }

View file

@ -8,6 +8,9 @@
*/ */
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Core\Config\Configuration;
/** /**
* @brief Arbitrary system configuration storage * @brief Arbitrary system configuration storage
* *
@ -15,23 +18,8 @@ namespace Friendica\Core;
* If we ever would decide to return exactly the variable type as entered, * If we ever would decide to return exactly the variable type as entered,
* we will have fun with the additional features. :-) * we will have fun with the additional features. :-)
*/ */
class Config class Config extends BaseObject
{ {
/**
* @var Config\Configuration
*/
private static $config;
/**
* Initialize the config
*
* @param Config\Configuration $config
*/
public static function init(Config\Configuration $config)
{
self::$config = $config;
}
/** /**
* @brief Loads all configuration values of family into a cached storage. * @brief Loads all configuration values of family into a cached storage.
* *
@ -41,7 +29,7 @@ class Config
*/ */
public static function load($cat = "config") public static function load($cat = "config")
{ {
self::$config->load($cat); self::getClass(Configuration::class)->load($cat);
} }
/** /**
@ -57,7 +45,7 @@ class Config
*/ */
public static function get($cat, $key, $default_value = null, $refresh = false) public static function get($cat, $key, $default_value = null, $refresh = false)
{ {
return self::$config->get($cat, $key, $default_value, $refresh); return self::getClass(Configuration::class)->get($cat, $key, $default_value, $refresh);
} }
/** /**
@ -75,7 +63,7 @@ class Config
*/ */
public static function set($cat, $key, $value) public static function set($cat, $key, $value)
{ {
return self::$config->set($cat, $key, $value); return self::getClass(Configuration::class)->set($cat, $key, $value);
} }
/** /**
@ -88,6 +76,6 @@ class Config
*/ */
public static function delete($cat, $key) public static function delete($cat, $key)
{ {
return self::$config->delete($cat, $key); return self::getClass(Configuration::class)->delete($cat, $key);
} }
} }

View file

@ -7,10 +7,9 @@ namespace Friendica\Core;
use DOMDocument; use DOMDocument;
use Exception; use Exception;
use Friendica\Core\Config\Cache\ConfigCache; use Friendica\Core\Config\Cache\ConfigCache;
use Friendica\Database\Database; use Friendica\Database\DBA;
use Friendica\Database\DBStructure; use Friendica\Database\DBStructure;
use Friendica\Object\Image; use Friendica\Object\Image;
use Friendica\Util\Logger\VoidLogger;
use Friendica\Util\Network; use Friendica\Util\Network;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Friendica\Util\Strings; use Friendica\Util\Strings;
@ -600,9 +599,9 @@ class Installer
*/ */
public function checkDB(ConfigCache $configCache, Profiler $profiler) public function checkDB(ConfigCache $configCache, Profiler $profiler)
{ {
$database = new Database($configCache, $profiler, new VoidLogger()); DBA::reconnect();
if ($database->connected()) { if (DBA::connected()) {
if (DBStructure::existsTable('user')) { if (DBStructure::existsTable('user')) {
$this->addCheck(L10n::t('Database already in use.'), false, true, ''); $this->addCheck(L10n::t('Database already in use.'), false, true, '');

View file

@ -4,29 +4,15 @@
*/ */
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Core\L10n\L10n as L10nClass; use Friendica\Core\L10n\L10n as L10nClass;
/** /**
* Provide Language, Translation, and Localization functions to the application * Provide Language, Translation, and Localization functions to the application
* Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N"). * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
*/ */
class L10n class L10n extends BaseObject
{ {
/**
* @var L10nClass
*/
private static $l10n;
/**
* Initializes the L10n static wrapper with the instance
*
* @param L10nClass $l10n The l10n class
*/
public static function init(L10nClass $l10n)
{
self::$l10n = $l10n;
}
/** /**
* Returns the current language code * Returns the current language code
* *
@ -34,7 +20,7 @@ class L10n
*/ */
public static function getCurrentLang() public static function getCurrentLang()
{ {
return self::$l10n->getCurrentLang(); return self::getClass(L10nClass::class)->getCurrentLang();
} }
/** /**
@ -52,7 +38,7 @@ class L10n
*/ */
public static function pushLang($lang) public static function pushLang($lang)
{ {
self::$l10n->pushLang($lang); self::getClass(L10nClass::class)->pushLang($lang);
} }
/** /**
@ -60,7 +46,7 @@ class L10n
*/ */
public static function popLang() public static function popLang()
{ {
self::$l10n->popLang(); self::getClass(L10nClass::class)->popLang();
} }
/** /**
@ -81,7 +67,7 @@ class L10n
*/ */
public static function t($s, ...$vars) public static function t($s, ...$vars)
{ {
return self::$l10n->t($s, ...$vars); return self::getClass(L10nClass::class)->t($s, ...$vars);
} }
/** /**
@ -105,7 +91,7 @@ class L10n
*/ */
public static function tt(string $singular, string $plural, int $count) public static function tt(string $singular, string $plural, int $count)
{ {
return self::$l10n->tt($singular, $plural, $count); return self::getClass(L10nClass::class)->tt($singular, $plural, $count);
} }
/** /**
@ -121,7 +107,7 @@ class L10n
*/ */
public static function getAvailableLanguages() public static function getAvailableLanguages()
{ {
return self::$l10n::getAvailableLanguages(); return L10nClass::getAvailableLanguages();
} }
/** /**
@ -132,7 +118,7 @@ class L10n
*/ */
public static function getDay($s) public static function getDay($s)
{ {
return self::$l10n->getDay($s); return self::getClass(L10nClass::class)->getDay($s);
} }
/** /**
@ -143,6 +129,6 @@ class L10n
*/ */
public static function getDayShort($s) public static function getDayShort($s)
{ {
return self::$l10n->getDayShort($s); return self::getClass(L10nClass::class)->getDayShort($s);
} }
} }

View file

@ -59,8 +59,6 @@ class L10n
$this->logger = $logger; $this->logger = $logger;
$this->loadTranslationTable(L10n::detectLanguage($config->get('system', 'language', 'en'))); $this->loadTranslationTable(L10n::detectLanguage($config->get('system', 'language', 'en')));
\Friendica\Core\L10n::init($this);
} }
/** /**

View file

@ -4,13 +4,15 @@
*/ */
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Util\Logger\WorkerLogger;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
/** /**
* @brief Logger functions * @brief Logger functions
*/ */
class Logger class Logger extends BaseObject
{ {
/** /**
* @see Logger::error() * @see Logger::error()
@ -37,6 +39,19 @@ class Logger
*/ */
const ALL = LogLevel::DEBUG; const ALL = LogLevel::DEBUG;
/**
* @var LoggerInterface The default Logger type
*/
const TYPE_LOGGER = LoggerInterface::class;
/**
* @var WorkerLogger A specific worker logger type, which can be anabled
*/
const TYPE_WORKER = WorkerLogger::class;
/**
* @var LoggerInterface The current logger type
*/
private static $type = self::TYPE_LOGGER;
/** /**
* @var array the legacy loglevels * @var array the legacy loglevels
* @deprecated 2019.03 use PSR-3 loglevels * @deprecated 2019.03 use PSR-3 loglevels
@ -53,33 +68,24 @@ class Logger
]; ];
/** /**
* @var LoggerInterface A PSR-3 compliant logger instance * Enable additional logging for worker usage
*/
private static $logger;
/**
* @var LoggerInterface A PSR-3 compliant logger instance for developing only
*/
private static $devLogger;
/**
* Sets the default logging handler for Friendica.
* *
* @param LoggerInterface $logger The Logger instance of this Application * @param string $functionName The worker function, which got called
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function init(LoggerInterface $logger) public static function enableWorker(string $functionName)
{ {
self::$logger = $logger; self::$type = self::TYPE_WORKER;
self::getClass(self::$type)->setFunctionName($functionName);
} }
/** /**
* Sets the default dev-logging handler for Friendica. * Disable additional logging for worker usage
*
* @param LoggerInterface $logger The Logger instance of this Application
*/ */
public static function setDevLogger(LoggerInterface $logger) public static function disableWorker()
{ {
self::$devLogger = $logger; self::$type = self::TYPE_LOGGER;
} }
/** /**
@ -95,7 +101,7 @@ class Logger
*/ */
public static function emergency($message, $context = []) public static function emergency($message, $context = [])
{ {
self::$logger->emergency($message, $context); self::getClass(self::$type)->emergency($message, $context);
} }
/** /**
@ -113,7 +119,7 @@ class Logger
*/ */
public static function alert($message, $context = []) public static function alert($message, $context = [])
{ {
self::$logger->alert($message, $context); self::getClass(self::$type)->alert($message, $context);
} }
/** /**
@ -130,7 +136,7 @@ class Logger
*/ */
public static function critical($message, $context = []) public static function critical($message, $context = [])
{ {
self::$logger->critical($message, $context); self::getClass(self::$type)->critical($message, $context);
} }
/** /**
@ -146,7 +152,7 @@ class Logger
*/ */
public static function error($message, $context = []) public static function error($message, $context = [])
{ {
self::$logger->error($message, $context); self::getClass(self::$type)->error($message, $context);
} }
/** /**
@ -164,7 +170,7 @@ class Logger
*/ */
public static function warning($message, $context = []) public static function warning($message, $context = [])
{ {
self::$logger->warning($message, $context); self::getClass(self::$type)->warning($message, $context);
} }
/** /**
@ -179,7 +185,7 @@ class Logger
*/ */
public static function notice($message, $context = []) public static function notice($message, $context = [])
{ {
self::$logger->notice($message, $context); self::getClass(self::$type)->notice($message, $context);
} }
/** /**
@ -196,7 +202,7 @@ class Logger
*/ */
public static function info($message, $context = []) public static function info($message, $context = [])
{ {
self::$logger->info($message, $context); self::getClass(self::$type)->info($message, $context);
} }
/** /**
@ -211,7 +217,7 @@ class Logger
*/ */
public static function debug($message, $context = []) public static function debug($message, $context = [])
{ {
self::$logger->debug($message, $context); self::getClass(self::$type)->debug($message, $context);
} }
/** /**
@ -225,7 +231,7 @@ class Logger
*/ */
public static function log($msg, $level = LogLevel::INFO) public static function log($msg, $level = LogLevel::INFO)
{ {
self::$logger->log($level, $msg); self::getClass(self::$type)->log($level, $msg);
} }
/** /**
@ -240,10 +246,6 @@ class Logger
*/ */
public static function devLog($msg, $level = LogLevel::DEBUG) public static function devLog($msg, $level = LogLevel::DEBUG)
{ {
if (!isset(self::$devLogger)) { self::getClass('$devLogger')->log($level, $msg);
return;
}
self::$devLogger->log($level, $msg);
} }
} }

View file

@ -8,6 +8,9 @@
*/ */
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Core\Config\PConfiguration;
/** /**
* @brief Management of user configuration storage * @brief Management of user configuration storage
* Note: * Note:
@ -15,23 +18,8 @@ namespace Friendica\Core;
* The PConfig::get() functions return boolean false for keys that are unset, * The PConfig::get() functions return boolean false for keys that are unset,
* and this could lead to subtle bugs. * and this could lead to subtle bugs.
*/ */
class PConfig class PConfig extends BaseObject
{ {
/**
* @var Config\PConfiguration
*/
private static $config;
/**
* Initialize the config with only the cache
*
* @param Config\PConfiguration $config The configuration cache
*/
public static function init(Config\PConfiguration $config)
{
self::$config = $config;
}
/** /**
* @brief Loads all configuration values of a user's config family into a cached storage. * @brief Loads all configuration values of a user's config family into a cached storage.
* *
@ -42,7 +30,7 @@ class PConfig
*/ */
public static function load(int $uid, string $cat) public static function load(int $uid, string $cat)
{ {
self::$config->load($uid, $cat); self::getClass(PConfiguration::class)->load($uid, $cat);
} }
/** /**
@ -59,7 +47,7 @@ class PConfig
*/ */
public static function get(int $uid, string $cat, string $key, $default_value = null, bool $refresh = false) public static function get(int $uid, string $cat, string $key, $default_value = null, bool $refresh = false)
{ {
return self::$config->get($uid, $cat, $key, $default_value, $refresh); return self::getClass(PConfiguration::class)->get($uid, $cat, $key, $default_value, $refresh);
} }
/** /**
@ -74,7 +62,7 @@ class PConfig
*/ */
public static function set(int $uid, string $cat, string $key, $value) public static function set(int $uid, string $cat, string $key, $value)
{ {
return self::$config->set($uid, $cat, $key, $value); return self::getClass(PConfiguration::class)->set($uid, $cat, $key, $value);
} }
/** /**
@ -88,6 +76,6 @@ class PConfig
*/ */
public static function delete(int $uid, string $cat, string $key) public static function delete(int $uid, string $cat, string $key)
{ {
return self::$config->delete($uid, $cat, $key); return self::getClass(PConfiguration::class)->delete($uid, $cat, $key);
} }
} }

View file

@ -8,7 +8,6 @@ use Friendica\BaseObject;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Process; use Friendica\Model\Process;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use Friendica\Util\Logger\WorkerLogger;
use Friendica\Util\Network; use Friendica\Util\Network;
/** /**
@ -378,10 +377,9 @@ class Worker
$argc = count($argv); $argc = count($argv);
$logger = $a->getLogger(); Logger::enableWorker($funcname);
$workerLogger = new WorkerLogger($logger, $funcname);
$workerLogger ->info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]); Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
@ -397,13 +395,13 @@ class Worker
unset($_SESSION); unset($_SESSION);
// Set the workerLogger as new default logger // Set the workerLogger as new default logger
Logger::init($workerLogger);
if ($method_call) { if ($method_call) {
call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv); call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
} else { } else {
$funcname($argv, $argc); $funcname($argv, $argc);
} }
Logger::init($logger);
Logger::disableWorker();
unset($a->queue); unset($a->queue);
@ -423,7 +421,7 @@ class Worker
$rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2); $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
$exec = round($duration, 2); $exec = round($duration, 2);
$logger->info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]); Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
self::$up_start = microtime(true); self::$up_start = microtime(true);
self::$db_duration = 0; self::$db_duration = 0;
@ -433,23 +431,23 @@ class Worker
self::$lock_duration = 0; self::$lock_duration = 0;
if ($duration > 3600) { if ($duration > 3600) {
$logger->info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]); Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
} elseif ($duration > 600) { } elseif ($duration > 600) {
$logger->info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]); Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
} elseif ($duration > 300) { } elseif ($duration > 300) {
$logger->info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]); Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
} elseif ($duration > 120) { } elseif ($duration > 120) {
$logger->info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]); Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
} }
$workerLogger->info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]); Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
$a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname); $a->getProfiler()->saveLog($a->getLogger(), "ID " . $queue["id"] . ": " . $funcname);
$cooldown = Config::get("system", "worker_cooldown", 0); $cooldown = Config::get("system", "worker_cooldown", 0);
if ($cooldown > 0) { if ($cooldown > 0) {
$logger->info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]); Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
sleep($cooldown); sleep($cooldown);
} }
} }

View file

@ -2,6 +2,7 @@
namespace Friendica\Database; namespace Friendica\Database;
use Friendica\BaseObject;
use mysqli; use mysqli;
use mysqli_result; use mysqli_result;
use mysqli_stmt; use mysqli_stmt;
@ -13,7 +14,7 @@ use PDOStatement;
* *
* This class is for the low level database stuff that does driver specific things. * This class is for the low level database stuff that does driver specific things.
*/ */
class DBA class DBA extends BaseObject
{ {
/** /**
* Lowest possible date value * Lowest possible date value
@ -24,19 +25,9 @@ class DBA
*/ */
const NULL_DATETIME = '0001-01-01 00:00:00'; const NULL_DATETIME = '0001-01-01 00:00:00';
/**
* @var Database
*/
private static $database;
public static function init(Database $database)
{
self::$database = $database;
}
public static function connect() public static function connect()
{ {
return self::$database->connect(); return self::getClass(Database::class)->connect();
} }
/** /**
@ -44,7 +35,7 @@ class DBA
*/ */
public static function disconnect() public static function disconnect()
{ {
self::$database->disconnect(); self::getClass(Database::class)->disconnect();
} }
/** /**
@ -52,7 +43,7 @@ class DBA
*/ */
public static function reconnect() public static function reconnect()
{ {
return self::$database->reconnect(); return self::getClass(Database::class)->reconnect();
} }
/** /**
@ -61,7 +52,7 @@ class DBA
*/ */
public static function getConnection() public static function getConnection()
{ {
return self::$database->getConnection(); return self::getClass(Database::class)->getConnection();
} }
/** /**
@ -74,7 +65,7 @@ class DBA
*/ */
public static function serverInfo() public static function serverInfo()
{ {
return self::$database->serverInfo(); return self::getClass(Database::class)->serverInfo();
} }
/** /**
@ -85,17 +76,17 @@ class DBA
*/ */
public static function databaseName() public static function databaseName()
{ {
return self::$database->databaseName(); return self::getClass(Database::class)->databaseName();
} }
public static function escape($str) public static function escape($str)
{ {
return self::$database->escape($str); return self::getClass(Database::class)->escape($str);
} }
public static function connected() public static function connected()
{ {
return self::$database->connected(); return self::getClass(Database::class)->connected();
} }
/** /**
@ -111,7 +102,7 @@ class DBA
*/ */
public static function anyValueFallback($sql) public static function anyValueFallback($sql)
{ {
return self::$database->anyValueFallback($sql); return self::getClass(Database::class)->anyValueFallback($sql);
} }
/** /**
@ -167,7 +158,7 @@ class DBA
{ {
$params = self::getParam(func_get_args()); $params = self::getParam(func_get_args());
return self::$database->p($sql, $params); return self::getClass(Database::class)->p($sql, $params);
} }
/** /**
@ -183,7 +174,7 @@ class DBA
$params = self::getParam(func_get_args()); $params = self::getParam(func_get_args());
return self::$database->e($sql, $params); return self::getClass(Database::class)->e($sql, $params);
} }
/** /**
@ -197,7 +188,7 @@ class DBA
*/ */
public static function exists($table, $condition) public static function exists($table, $condition)
{ {
return self::$database->exists($table, $condition); return self::getClass(Database::class)->exists($table, $condition);
} }
/** /**
@ -214,7 +205,7 @@ class DBA
{ {
$params = self::getParam(func_get_args()); $params = self::getParam(func_get_args());
return self::$database->fetchFirst($sql, $params); return self::getClass(Database::class)->fetchFirst($sql, $params);
} }
/** /**
@ -224,7 +215,7 @@ class DBA
*/ */
public static function affectedRows() public static function affectedRows()
{ {
return self::$database->affectedRows(); return self::getClass(Database::class)->affectedRows();
} }
/** /**
@ -235,7 +226,7 @@ class DBA
*/ */
public static function columnCount($stmt) public static function columnCount($stmt)
{ {
return self::$database->columnCount($stmt); return self::getClass(Database::class)->columnCount($stmt);
} }
/** /**
* @brief Returns the number of rows of a statement * @brief Returns the number of rows of a statement
@ -245,7 +236,7 @@ class DBA
*/ */
public static function numRows($stmt) public static function numRows($stmt)
{ {
return self::$database->numRows($stmt); return self::getClass(Database::class)->numRows($stmt);
} }
/** /**
@ -256,7 +247,7 @@ class DBA
*/ */
public static function fetch($stmt) public static function fetch($stmt)
{ {
return self::$database->fetch($stmt); return self::getClass(Database::class)->fetch($stmt);
} }
/** /**
@ -271,7 +262,7 @@ class DBA
*/ */
public static function insert($table, $param, $on_duplicate_update = false) public static function insert($table, $param, $on_duplicate_update = false)
{ {
return self::$database->insert($table, $param, $on_duplicate_update); return self::getClass(Database::class)->insert($table, $param, $on_duplicate_update);
} }
/** /**
@ -281,7 +272,7 @@ class DBA
*/ */
public static function lastInsertId() public static function lastInsertId()
{ {
return self::$database->lastInsertId(); return self::getClass(Database::class)->lastInsertId();
} }
/** /**
@ -296,7 +287,7 @@ class DBA
*/ */
public static function lock($table) public static function lock($table)
{ {
return self::$database->lock($table); return self::getClass(Database::class)->lock($table);
} }
/** /**
@ -307,7 +298,7 @@ class DBA
*/ */
public static function unlock() public static function unlock()
{ {
return self::$database->unlock(); return self::getClass(Database::class)->unlock();
} }
/** /**
@ -317,7 +308,7 @@ class DBA
*/ */
public static function transaction() public static function transaction()
{ {
return self::$database->transaction(); return self::getClass(Database::class)->transaction();
} }
/** /**
@ -327,7 +318,7 @@ class DBA
*/ */
public static function commit() public static function commit()
{ {
return self::$database->commit(); return self::getClass(Database::class)->commit();
} }
/** /**
@ -337,7 +328,7 @@ class DBA
*/ */
public static function rollback() public static function rollback()
{ {
return self::$database->rollback(); return self::getClass(Database::class)->rollback();
} }
/** /**
@ -354,7 +345,7 @@ class DBA
*/ */
public static function delete($table, array $conditions, array $options = []) public static function delete($table, array $conditions, array $options = [])
{ {
return self::$database->delete($table, $conditions, $options); return self::getClass(Database::class)->delete($table, $conditions, $options);
} }
/** /**
@ -388,7 +379,7 @@ class DBA
*/ */
public static function update($table, $fields, $condition, $old_fields = []) public static function update($table, $fields, $condition, $old_fields = [])
{ {
return self::$database->update($table, $fields, $condition, $old_fields); return self::getClass(Database::class)->update($table, $fields, $condition, $old_fields);
} }
/** /**
@ -405,7 +396,7 @@ class DBA
*/ */
public static function selectFirst($table, array $fields = [], array $condition = [], $params = []) public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
{ {
return self::$database->selectFirst($table, $fields, $condition, $params); return self::getClass(Database::class)->selectFirst($table, $fields, $condition, $params);
} }
/** /**
@ -450,7 +441,7 @@ class DBA
*/ */
public static function select($table, array $fields = [], array $condition = [], array $params = []) public static function select($table, array $fields = [], array $condition = [], array $params = [])
{ {
return self::$database->select($table, $fields, $condition, $params); return self::getClass(Database::class)->select($table, $fields, $condition, $params);
} }
/** /**
@ -473,7 +464,7 @@ class DBA
*/ */
public static function count($table, array $condition = []) public static function count($table, array $condition = [])
{ {
return self::$database->count($table, $condition); return self::getClass(Database::class)->count($table, $condition);
} }
/** /**
@ -605,7 +596,7 @@ class DBA
*/ */
public static function toArray($stmt, $do_close = true) public static function toArray($stmt, $do_close = true)
{ {
return self::$database->toArray($stmt, $do_close); return self::getClass(Database::class)->toArray($stmt, $do_close);
} }
/** /**
@ -615,7 +606,7 @@ class DBA
*/ */
public static function errorNo() public static function errorNo()
{ {
return self::$database->errorNo(); return self::getClass(Database::class)->errorNo();
} }
/** /**
@ -625,7 +616,7 @@ class DBA
*/ */
public static function errorMessage() public static function errorMessage()
{ {
return self::$database->errorMessage(); return self::getClass(Database::class)->errorMessage();
} }
/** /**
@ -636,7 +627,7 @@ class DBA
*/ */
public static function close($stmt) public static function close($stmt)
{ {
return self::$database->close($stmt); return self::getClass(Database::class)->close($stmt);
} }
/** /**
@ -649,7 +640,7 @@ class DBA
*/ */
public static function processlist() public static function processlist()
{ {
return self::$database->processlist(); return self::getClass(Database::class)->processlist();
} }
/** /**
@ -661,7 +652,7 @@ class DBA
*/ */
public static function isResult($array) public static function isResult($array)
{ {
return self::$database->isResult($array); return self::getClass(Database::class)->isResult($array);
} }
/** /**
@ -673,6 +664,6 @@ class DBA
*/ */
public static function escapeArray(&$arr, $add_quotation = false) public static function escapeArray(&$arr, $add_quotation = false)
{ {
return self::$database->escapeArray($arr, $add_quotation); return self::getClass(Database::class)->escapeArray($arr, $add_quotation);
} }
} }

View file

@ -56,8 +56,6 @@ class Database
$this->readServerVariables($server); $this->readServerVariables($server);
$this->connect(); $this->connect();
DBA::init($this);
if ($this->isConnected()) { if ($this->isConnected()) {
// Loads DB_UPDATE_VERSION constant // Loads DB_UPDATE_VERSION constant
DBStructure::definition($configCache->get('system', 'basepath'), false); DBStructure::definition($configCache->get('system', 'basepath'), false);

View file

@ -2,7 +2,6 @@
namespace Friendica\Factory; namespace Friendica\Factory;
use Friendica\Core;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Config\Cache; use Friendica\Core\Config\Cache;
use Friendica\Model\Config\Config as ConfigModel; use Friendica\Model\Config\Config as ConfigModel;
@ -39,9 +38,6 @@ class ConfigFactory
} }
// Set the config in the static container for legacy usage
Core\Config::init($configuration);
return $configuration; return $configuration;
} }
@ -60,9 +56,6 @@ class ConfigFactory
$configuration = new Config\JitPConfiguration($pConfigCache, $configModel); $configuration = new Config\JitPConfiguration($pConfigCache, $configModel);
} }
// Set the config in the static container for legacy usage
Core\PConfig::init($configuration);
return $configuration; return $configuration;
} }
} }

View file

@ -1,30 +0,0 @@
<?php
namespace Friendica\Factory;
use Dice\Dice;
use Friendica\App;
use Friendica\Core\Config\PConfiguration;
use Psr\Log\LoggerInterface;
class DependencyFactory
{
/**
* Setting all default-dependencies of a friendica execution
*
* @param string $channel The channel of this execution
* @param bool $isBackend True, if it's a backend execution, otherwise false (Default true)
*
* @return App The application
*
* @throws \Exception
*/
public static function setUp($channel, Dice $dice, $isBackend = true)
{
$pConfig = $dice->create(PConfiguration::class);
$logger = $dice->create(LoggerInterface::class, [$channel]);
$devLogger = $dice->create('$devLogger', [$channel]);
return $dice->create(App::class, [$isBackend]);
}
}

View file

@ -25,6 +25,8 @@ use Psr\Log\LogLevel;
*/ */
class LoggerFactory class LoggerFactory
{ {
const DEV_CHANNEL = 'dev';
/** /**
* A list of classes, which shouldn't get logged * A list of classes, which shouldn't get logged
* *
@ -36,10 +38,19 @@ class LoggerFactory
'Friendica\\Util\\Logger', 'Friendica\\Util\\Logger',
]; ];
/**
* Retrieve the channel based on the __FILE__
*
* @return string
*/
private function findChannel()
{
return basename($_SERVER['PHP_SELF'], '.php');
}
/** /**
* Creates a new PSR-3 compliant logger instances * Creates a new PSR-3 compliant logger instances
* *
* @param string $channel The channel of the logger instance
* @param Configuration $config The config * @param Configuration $config The config
* @param Profiler $profiler The profiler of the app * @param Profiler $profiler The profiler of the app
* *
@ -48,12 +59,11 @@ class LoggerFactory
* @throws \Exception * @throws \Exception
* @throws InternalServerErrorException * @throws InternalServerErrorException
*/ */
public function create($channel, Database $database, Configuration $config, Profiler $profiler) public function create(Database $database, Configuration $config, Profiler $profiler)
{ {
if (empty($config->get('system', 'debugging', false))) { if (empty($config->get('system', 'debugging', false))) {
$logger = new VoidLogger(); $logger = new VoidLogger();
$database->setLogger($logger); $database->setLogger($logger);
Logger::init($logger);
return $logger; return $logger;
} }
@ -66,7 +76,7 @@ class LoggerFactory
$loggerTimeZone = new \DateTimeZone('UTC'); $loggerTimeZone = new \DateTimeZone('UTC');
Monolog\Logger::setTimezone($loggerTimeZone); Monolog\Logger::setTimezone($loggerTimeZone);
$logger = new Monolog\Logger($channel); $logger = new Monolog\Logger($this->findChannel());
$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor()); $logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
$logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor()); $logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
$logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushProcessor(new Monolog\Processor\UidProcessor());
@ -81,7 +91,7 @@ class LoggerFactory
break; break;
case 'syslog': case 'syslog':
$logger = new SyslogLogger($channel, $introspection, $loglevel); $logger = new SyslogLogger($this->findChannel(), $introspection, $loglevel);
break; break;
case 'stream': case 'stream':
@ -89,7 +99,7 @@ class LoggerFactory
$stream = $config->get('system', 'logfile'); $stream = $config->get('system', 'logfile');
// just add a stream in case it's either writable or not file // just add a stream in case it's either writable or not file
if (!is_file($stream) || is_writable($stream)) { if (!is_file($stream) || is_writable($stream)) {
$logger = new StreamLogger($channel, $stream, $introspection, $loglevel); $logger = new StreamLogger($this->findChannel(), $stream, $introspection, $loglevel);
} else { } else {
$logger = new VoidLogger(); $logger = new VoidLogger();
} }
@ -104,8 +114,6 @@ class LoggerFactory
} }
$database->setLogger($logger); $database->setLogger($logger);
Logger::init($logger);
return $logger; return $logger;
} }
@ -117,7 +125,6 @@ class LoggerFactory
* *
* It should never get filled during normal usage of Friendica * It should never get filled during normal usage of Friendica
* *
* @param string $channel The channel of the logger instance
* @param Configuration $config The config * @param Configuration $config The config
* @param Profiler $profiler The profiler of the app * @param Profiler $profiler The profiler of the app
* *
@ -126,7 +133,7 @@ class LoggerFactory
* @throws InternalServerErrorException * @throws InternalServerErrorException
* @throws \Exception * @throws \Exception
*/ */
public static function createDev($channel, Configuration $config, Profiler $profiler) public static function createDev(Configuration $config, Profiler $profiler)
{ {
$debugging = $config->get('system', 'debugging'); $debugging = $config->get('system', 'debugging');
$stream = $config->get('system', 'dlogfile'); $stream = $config->get('system', 'dlogfile');
@ -135,7 +142,6 @@ class LoggerFactory
if ((!isset($developerIp) || !$debugging) && if ((!isset($developerIp) || !$debugging) &&
(!is_file($stream) || is_writable($stream))) { (!is_file($stream) || is_writable($stream))) {
$logger = new VoidLogger(); $logger = new VoidLogger();
Logger::setDevLogger($logger);
return $logger; return $logger;
} }
@ -150,7 +156,7 @@ class LoggerFactory
$loggerTimeZone = new \DateTimeZone('UTC'); $loggerTimeZone = new \DateTimeZone('UTC');
Monolog\Logger::setTimezone($loggerTimeZone); Monolog\Logger::setTimezone($loggerTimeZone);
$logger = new Monolog\Logger($channel); $logger = new Monolog\Logger(self::DEV_CHANNEL);
$logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor()); $logger->pushProcessor(new Monolog\Processor\PsrLogMessageProcessor());
$logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor()); $logger->pushProcessor(new Monolog\Processor\ProcessIdProcessor());
$logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushProcessor(new Monolog\Processor\UidProcessor());
@ -162,12 +168,12 @@ class LoggerFactory
break; break;
case 'syslog': case 'syslog':
$logger = new SyslogLogger($channel, $introspection, LogLevel::DEBUG); $logger = new SyslogLogger(self::DEV_CHANNEL, $introspection, LogLevel::DEBUG);
break; break;
case 'stream': case 'stream':
default: default:
$logger = new StreamLogger($channel, $stream, $introspection, LogLevel::DEBUG); $logger = new StreamLogger(self::DEV_CHANNEL, $stream, $introspection, LogLevel::DEBUG);
break; break;
} }
@ -178,8 +184,6 @@ class LoggerFactory
$logger = new ProfilerLogger($logger, $profiler); $logger = new ProfilerLogger($logger, $profiler);
} }
Logger::setDevLogger($logger);
return $logger; return $logger;
} }

View file

@ -31,13 +31,23 @@ class WorkerLogger implements LoggerInterface
* @param string $functionName The current function name of the worker * @param string $functionName The current function name of the worker
* @param int $idLength The length of the generated worker ID * @param int $idLength The length of the generated worker ID
*/ */
public function __construct(LoggerInterface $logger, $functionName, $idLength = 7) public function __construct(LoggerInterface $logger, $functionName = '', $idLength = 7)
{ {
$this->logger = $logger; $this->logger = $logger;
$this->functionName = $functionName; $this->functionName = $functionName;
$this->workerId = Strings::getRandomHex($idLength); $this->workerId = Strings::getRandomHex($idLength);
} }
/**
* Sets the function name for additional logging
*
* @param string $functionName
*/
public function setFunctionName(string $functionName)
{
$this->functionName = $functionName;
}
/** /**
* Adds the worker context for each log entry * Adds the worker context for each log entry
* *