-
Notifications
You must be signed in to change notification settings - Fork 1
/
Singletons.php
52 lines (42 loc) · 1.2 KB
/
Singletons.php
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
<?php
/**
* This file is part of the Cervo package.
*
* Copyright (c) 2010-2018 Nevraxe inc. & Marc André Audet <maudet@nevraxe.com>.
*
* @package Cervo
* @author Marc André Audet <maaudet@nevraxe.com>
* @copyright 2010 - 2018 Nevraxe inc. & Marc André Audet
* @license See LICENSE.md BSD-2-Clauses
* @link https://github.com/Nevraxe/Cervo
* @since 5.0.0
*/
declare(strict_types=1);
namespace Cervo;
use Cervo\Exceptions\Singletons\InvalidClassException;
use Cervo\Interfaces\SingletonInterface;
use Cervo\Utils\ClassUtils;
/**
* Singletons manager for Cervo.
*
* @author Marc André Audet <maudet@nevraxe.com>
*/
final class Singletons
{
private $objects = [];
private $context;
public function __construct(Context $context)
{
$this->context = $context;
}
public function get(string $className): SingletonInterface
{
if (is_object($this->objects[$className])) {
return $this->objects[$className];
}
if (!ClassUtils::implements($className, SingletonInterface::class)) {
throw new InvalidClassException();
}
return ($this->objects[$className] = new $className($this->context));
}
}