Implemented container

This commit is contained in:
Igor Scheller 2017-08-31 17:30:54 +02:00
parent 0a20883aa8
commit 8c81adc8e8
14 changed files with 175 additions and 97 deletions

3
.gitignore vendored
View File

@ -14,8 +14,9 @@ Thumbs.db
_vimrc_local.vim _vimrc_local.vim
.sass-cache .sass-cache
# PHPstorm config # PHPstorm files
/.idea/ /.idea/
/.phpstorm.meta.php
# Project files # Project files
/config/config.php /config/config.php

View File

@ -17,7 +17,8 @@
"php": ">=7.0.0", "php": ">=7.0.0",
"erusev/parsedown": "1.6.*", "erusev/parsedown": "1.6.*",
"twbs/bootstrap": "^3.3", "twbs/bootstrap": "^3.3",
"symfony/http-foundation": "^3.3" "symfony/http-foundation": "^3.3",
"psr/container": "^1.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^6.3" "phpunit/phpunit": "^6.3"

View File

@ -1,11 +1,13 @@
<?php <?php
use Engelsystem\Config\Config; use Engelsystem\Config\Config;
use Engelsystem\Container\Container;
use Engelsystem\Database\Db; use Engelsystem\Database\Db;
use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Exceptions\Handler as ExceptionHandler;
use Engelsystem\Http\Request; use Engelsystem\Http\Request;
use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\HtmlEngine;
use Engelsystem\Renderer\Renderer; use Engelsystem\Renderer\Renderer;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Session;
/** /**
@ -14,11 +16,20 @@ use Symfony\Component\HttpFoundation\Session\Session;
require_once __DIR__ . '/autoload.php'; require_once __DIR__ . '/autoload.php';
/**
* Initialize the container
*/
$container = Container::getInstance();
$container->instance('container', $container);
$container->instance(ContainerInterface::class, $container);
/** /**
* Load configuration * Load configuration
*/ */
$config = new Config(); $config = new Config();
Config::setInstance($config); $container->instance('config', $config);
$config->set(require __DIR__ . '/../config/config.default.php'); $config->set(require __DIR__ . '/../config/config.default.php');
if (file_exists(__DIR__ . '/../config/config.php')) { if (file_exists(__DIR__ . '/../config/config.php')) {
@ -37,7 +48,8 @@ date_default_timezone_set($config->get('timezone'));
* @var Request $request * @var Request $request
*/ */
$request = Request::createFromGlobals(); $request = Request::createFromGlobals();
$request::setInstance($request); $container->instance('request', $request);
/** /**
* Check for maintenance * Check for maintenance
@ -52,14 +64,15 @@ if ($config->get('maintenance')) {
* Initialize renderer * Initialize renderer
*/ */
$renderer = new Renderer(); $renderer = new Renderer();
$container->instance('renderer', $renderer);
$renderer->addRenderer(new HtmlEngine()); $renderer->addRenderer(new HtmlEngine());
Renderer::setInstance($renderer);
/** /**
* Register error handler * Register error handler
*/ */
$errorHandler = new ExceptionHandler(); $errorHandler = new ExceptionHandler();
$container->instance('error.handler', $errorHandler);
if (config('environment') == 'development') { if (config('environment') == 'development') {
$errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT);
ini_set('display_errors', true); ini_set('display_errors', true);
@ -171,6 +184,7 @@ foreach ($includeFiles as $file) {
* Init application * Init application
*/ */
$session = new Session(); $session = new Session();
$container->instance('session', $session);
$session->start(); $session->start();
$request->setSession($session); $request->setSession($session);

View File

@ -1,7 +1,5 @@
<?php <?php
use Engelsystem\Http\Request;
/** /**
* Return currently active locale * Return currently active locale
* *
@ -65,7 +63,7 @@ function gettext_locale($locale = null)
*/ */
function make_langselect() function make_langselect()
{ {
$request = Request::getInstance(); $request = app('request');
$items = []; $items = [];
foreach (config('locales') as $locale => $name) { foreach (config('locales') as $locale => $name) {

View File

@ -1,7 +1,6 @@
<?php <?php
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Http\Request;
/** /**
* Publically available page to feed the news to feed readers * Publically available page to feed the news to feed readers
@ -45,7 +44,7 @@ function user_atom()
*/ */
function make_atom_entries_from_news($news_entries) function make_atom_entries_from_news($news_entries)
{ {
$request = Request::getInstance(); $request = app('request');
$html = '<?xml version="1.0" encoding="utf-8"?> $html = '<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"> <feed xmlns="http://www.w3.org/2005/Atom">
<title>Engelsystem</title> <title>Engelsystem</title>

View File

@ -1,7 +1,5 @@
<?php <?php
use Engelsystem\Http\Request;
require_once realpath(__DIR__ . '/../includes/engelsystem_provider.php'); require_once realpath(__DIR__ . '/../includes/engelsystem_provider.php');
$free_pages = [ $free_pages = [
@ -27,7 +25,6 @@ $page = '';
$title = ''; $title = '';
$content = ''; $content = '';
/** @var Request $request */
$page = $request->query->get('p'); $page = $request->query->get('p');
if (empty($page)) { if (empty($page)) {
$page = $request->path(); $page = $request->path();

View File

@ -2,15 +2,8 @@
namespace Engelsystem\Config; namespace Engelsystem\Config;
use ErrorException;
class Config class Config
{ {
/**
* @var self
*/
protected static $instance;
/** /**
* The config values * The config values
* *
@ -104,25 +97,4 @@ class Config
{ {
$this->remove($key); $this->remove($key);
} }
/**
* @return Config
* @throws ErrorException
*/
public static function getInstance()
{
if (!self::$instance instanceof self) {
throw new ErrorException('Config not initialized');
}
return self::$instance;
}
/**
* @param self $instance
*/
public static function setInstance($instance)
{
self::$instance = $instance;
}
} }

105
src/Container/Container.php Normal file
View File

@ -0,0 +1,105 @@
<?php
namespace Engelsystem\Container;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class Container implements ContainerInterface
{
/**
* The globally available container
*
* @var static
*/
protected static $instance;
/**
* Contains the shared instances
*
* @var mixed[]
*/
protected $instances = [];
/**
* Finds an entry of the container by its identifier and returns it
*
* @param string $id Identifier of the entry to look for
*
* @throws NotFoundExceptionInterface No entry was found for **this** identifier
* @throws ContainerExceptionInterface Error while retrieving the entry
*
* @return mixed Entry
*/
public function get($id)
{
if ($this->has($id)) {
return $this->resolve($id);
}
throw new NotFoundException(sprintf('The entry with the id "%s" could not be found'));
}
/**
* Register a shared entry in the container
*
* @param string $abstract Identifier of the entry to set
* @param mixed $instance Entry
*/
public function instance($abstract, $instance)
{
$this->instances[$abstract] = $instance;
}
/**
* Returns true if the container can return an entry for the given identifier
* Returns false otherwise
*
* `has($id)` returning true does not mean that `get($id)` will not throw an exception
* It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`
*
* @param string $id Identifier of the entry to look for
*
* @return bool
*/
public function has($id)
{
return isset($this->instances[$id]);
}
/**
* Get the globally available instance of the container
*
* @return Container
*/
public static function getInstance()
{
if (is_null(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
/**
* Set the globally available instance of the container
*
* @param Container $container
*/
public static function setInstance(Container $container)
{
static::$instance = $container;
}
/**
* Resolve the requested object
*
* @param string $abstract
* @return mixed
*/
protected function resolve($abstract)
{
return $this->instances[$abstract];
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace Engelsystem\Container;
use Exception;
use Psr\Container\ContainerExceptionInterface;
class ContainerException extends Exception implements ContainerExceptionInterface
{
}

View File

@ -0,0 +1,10 @@
<?php
namespace Engelsystem\Container;
use Psr\Container\NotFoundExceptionInterface;
class NotFoundException extends ContainerException implements NotFoundExceptionInterface
{
}

View File

@ -2,14 +2,10 @@
namespace Engelsystem\Http; namespace Engelsystem\Http;
use ErrorException;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest; use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class Request extends SymfonyRequest class Request extends SymfonyRequest
{ {
/** @var self */
protected static $instance;
/** /**
* Get POST input * Get POST input
* *
@ -68,25 +64,4 @@ class Request extends SymfonyRequest
{ {
return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/'); return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/');
} }
/**
* @return self
* @throws ErrorException
*/
public static function getInstance()
{
if (!self::$instance instanceof self) {
throw new ErrorException('Request not initialized');
}
return self::$instance;
}
/**
* @param self $instance
*/
public static function setInstance($instance)
{
self::$instance = $instance;
}
} }

View File

@ -2,13 +2,8 @@
namespace Engelsystem\Renderer; namespace Engelsystem\Renderer;
use ErrorException;
class Renderer class Renderer
{ {
/** @var self */
protected static $instance;
/** @var EngineInterface[] */ /** @var EngineInterface[] */
protected $renderer = []; protected $renderer = [];
@ -29,7 +24,7 @@ class Renderer
return $renderer->get($template, $data); return $renderer->get($template, $data);
} }
engelsystem_error('Unable to find a renderer for template file &laquo;' . $template . '&raquo;.'); engelsystem_error('Unable to find a renderer for template file "' . $template . '".');
return ''; return '';
} }
@ -42,21 +37,4 @@ class Renderer
{ {
$this->renderer[] = $renderer; $this->renderer[] = $renderer;
} }
/**
* @return self
* @throws ErrorException
*/
public static function getInstance()
{
return self::$instance;
}
/**
* @param self $instance
*/
public static function setInstance($instance)
{
self::$instance = $instance;
}
} }

View File

@ -2,8 +2,6 @@
namespace Engelsystem\Routing; namespace Engelsystem\Routing;
use Engelsystem\Http\Request;
class UrlGenerator class UrlGenerator
{ {
/** /**
@ -14,7 +12,7 @@ class UrlGenerator
public static function to($path, $parameters = []) public static function to($path, $parameters = [])
{ {
$path = '/' . ltrim($path, '/'); $path = '/' . ltrim($path, '/');
$request = Request::getInstance(); $request = app('request');
$uri = $request->getUriForPath($path); $uri = $request->getUriForPath($path);
if (!empty($parameters) && is_array($parameters)) { if (!empty($parameters) && is_array($parameters)) {

View File

@ -2,11 +2,27 @@
// Some useful functions // Some useful functions
use Engelsystem\Config\Config; use Engelsystem\Config\Config;
use Engelsystem\Container\Container;
use Engelsystem\Http\Request; use Engelsystem\Http\Request;
use Engelsystem\Renderer\Renderer; use Engelsystem\Renderer\Renderer;
use Engelsystem\Routing\UrlGenerator; use Engelsystem\Routing\UrlGenerator;
use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Get the global container instance
*
* @param string $id
* @return mixed
*/
function app($id = null)
{
if (is_null($id)) {
return Container::getInstance();
}
return Container::getInstance()->get($id);
}
/** /**
* Get or set config values * Get or set config values
* *
@ -16,15 +32,18 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
*/ */
function config($key = null, $default = null) function config($key = null, $default = null)
{ {
$config = app('config');
if (empty($key)) { if (empty($key)) {
return Config::getInstance(); return $config;
} }
if (is_array($key)) { if (is_array($key)) {
Config::getInstance()->set($key); $config->set($key);
return true;
} }
return Config::getInstance()->get($key, $default); return $config->get($key, $default);
} }
/** /**
@ -34,7 +53,7 @@ function config($key = null, $default = null)
*/ */
function request($key = null, $default = null) function request($key = null, $default = null)
{ {
$request = Request::getInstance(); $request = app('request');
if (is_null($key)) { if (is_null($key)) {
return $request; return $request;
@ -66,7 +85,7 @@ function session($key = null, $default = null)
*/ */
function view($template = null, $data = null) function view($template = null, $data = null)
{ {
$renderer = Renderer::getInstance(); $renderer = app('renderer');
if (is_null($template)) { if (is_null($template)) {
return $renderer; return $renderer;