1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
<?php
namespace Tev\Application;
use Closure;
use Pimple\Container;
use Tev\Contracts\BootstrapperInterface;
/**
* Tev plugin application.
*
* Service locator for all application services.
*/
class Application
{
/**
* Application instance.
*
* @var \Tev\Application\Application
*/
private static $instance = null;
/**
* DI container.
*
* @var \Pimple\Container
*/
private $container;
/**
* Array of default services to bootstrap.
*
* @var array
*/
protected $bootstraps = array(
'Tev\Application\Bootstrap\PluginLoader',
'Tev\Application\Bootstrap\AuthorFactory',
'Tev\Application\Bootstrap\Term',
'Tev\Application\Bootstrap\Taxonomy',
'Tev\Application\Bootstrap\FieldFactory',
'Tev\Application\Bootstrap\Post',
'Tev\Application\Bootstrap\Util'
);
/**
* Get the singleton application instance.
*
* @return \Tev\Application\Application
*/
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new static;
self::$instance->bootstrap();
}
return self::$instance;
}
/**
* Constructor.
*
* Private for singleton. Constructs container.
*
* @return void
*/
private function __construct()
{
$this->container = new Container;
}
/**
* Bind a service into the container.
*
* @param string $name Service name
* @param \Closure $bind Service location closure. Receives \Tev\Application\Application as argument
* @return \Tev\Application\Application This, for chaining
*/
public function bind($name, Closure $bind)
{
$app = $this;
$this->container[$name] = function ($c) use ($app, $bind) {
return $bind($app);
};
return $this;
}
/**
* Fetch a service from the container.
*
* @param string $name Service name
* @return mixed Bound service
*/
public function fetch($name)
{
return $this->container[$name];
}
/**
* Bootstrap default services into the container.
*
* @return \Tev\Application\Application This, for chaining
*/
protected function bootstrap()
{
foreach ($this->bootstraps as $bClass) {
$b = new $bClass;
if ($b instanceof BootstrapperInterface) {
$b->bootstrap($this);
}
}
return $this;
}
}