-
Notifications
You must be signed in to change notification settings - Fork 0
/
HelperRegistry.php
89 lines (79 loc) · 1.67 KB
/
HelperRegistry.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
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
<?php
/**
* slince console component
* @author Tao <[email protected]>
*/
namespace Slince\Console;
use Slince\Console\Helper\HelperInterface;
class HelperRegistry
{
/**
* 已经加载的helper
*
* @var array
*/
protected $loaded = [];
/**
* Console
*
* @var Console
*/
protected $console;
function __construct(Console $console)
{
$this->console = $console;
}
/**
* 加载helper,已存在的话会覆盖
*
* @param string $name
*/
function load($name)
{
$className = $this->resolveClassName($name);
$instance = $this->create($className);
return $this->loaded[$name] = $instance;
}
/**
* 自动获取helper,不存在会尝试创建
*
* @param string $name
* @return HelperInterface
*/
function get($name)
{
if (! isset($this->loaded[$name])) {
$this->load($name);
}
return $this->loaded[$name];
}
/**
* 处理helper的类名
* @param string $class
* @return string
*/
protected function resolveClassName($class)
{
return "\\Slince\\Console\\Helper\\{$class}Helper";
}
/**
* 创建helper对象
*
* @param string $className
* @return HelperInterface
*/
protected function create($className)
{
return new $className($this->console->getIo());
}
/**
* 直接注册一个helper实例
*
* @param string $name
* @param HelperInterface $helper
*/
function register($name, HelperInterface $helper)
{
$this->loaded[$name] = $helper;
}
}