Application.php 2.42 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program 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 General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

namespace Q2A\App;

21
use Q2A\Database\DbConnection;
22 23 24 25
use Q2A\Database\DbSelect;
use Q2A\Exceptions\FatalErrorException;
use Q2A\Http\Router;
use Q2A\Util\Set;
26 27 28

class Application
{
29 30 31 32 33
	/** @var Set */
	protected $services;

	/** @var Set */
	protected $dataStore;
34 35 36 37

	/** @var static */
	protected static $instance;

38
	protected function __construct()
39
	{
40 41
		$this->services = new Set();
		$this->dataStore = new Set();
42
		$this->registerCoreServices();
43 44 45 46 47 48 49 50
	}

	/**
	 * Instantiate and fetch the application as a singleton.
	 * @return static
	 */
	public static function getInstance()
	{
51
		if (static::$instance === null) {
52 53 54 55 56 57 58
			static::$instance = new static();
		}

		return static::$instance;
	}

	/**
59 60 61 62
	 * Return the specified service.
	 * @throws FatalErrorException
	 * @param string $key The key to look for
	 * @return mixed
63
	 */
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	public function getService($key)
	{
		$obj = $this->services->get($key);
		if ($obj === null) {
			throw new FatalErrorException(sprintf('Key "%s" not found in container', $key));
		}

		return $obj;
	}

	/**
	 * Adds a new service to the container.
	 * @param string $key The key to look for
	 * @param mixed $value The object to add
	 * @return void
	 */
	public function registerService($key, $value)
81
	{
82
		$this->services->set($key, $value);
83 84 85
	}

	/**
86
	 * Retrieve data from the global storage.
87
	 */
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
	public function getData($key)
	{
		return $this->dataStore->get($key);
	}

	/**
	 * Store some data in the global storage.
	 */
	public function setData($key, $value)
	{
		return $this->dataStore->set($key, $value);
	}

	/**
	 * Register the services used by the core.
	 */
	private function registerCoreServices()
105
	{
106 107 108 109
		$db = new DbConnection();
		$this->services->set('router', new Router());
		$this->services->set('database', $db);
		$this->services->set('dbselect', new DbSelect($db));
110 111
	}
}