1: <?php
2: /**
3: * The Horde_Cli_Modular_ModuleProvider:: class provides access to a single
4: * module.
5: *
6: * PHP version 5
7: *
8: * @category Horde
9: * @package Cli_Modular
10: * @author Gunnar Wrobel <wrobel@pardus.de>
11: * @license http://www.horde.org/licenses/lgpl21 LGPL
12: * @link http://www.horde.org/libraries/Horde_Cli_Modular
13: */
14:
15: /**
16: * The Horde_Cli_Modular_ModuleProvider:: class provides access to a single
17: * module.
18: *
19: * Copyright 2010-2012 Horde LLC (http://www.horde.org/)
20: *
21: * See the enclosed file COPYING for license information (LGPL). If you
22: * did not receive this file, see http://www.horde.org/licenses/lgpl21.
23: *
24: * @category Horde
25: * @package Cli_Modular
26: * @author Gunnar Wrobel <wrobel@pardus.de>
27: * @license http://www.horde.org/licenses/lgpl21 LGPL 2.1
28: * @link http://www.horde.org/libraries/Horde_Cli_Modular
29: */
30: class Horde_Cli_Modular_ModuleProvider
31: {
32: /**
33: * Class prefix.
34: *
35: * @var string
36: */
37: private $_prefix;
38:
39: /**
40: * Constructor argument for CLI modules. Likely to be a Horde_Injector
41: * instance.
42: *
43: * @var mixed
44: */
45: private $_dependencies;
46:
47: /**
48: * A cache for initialized module instances.
49: *
50: * @var array
51: */
52: private $_instances;
53:
54: /**
55: * Constructor.
56: *
57: * @param array $parameters Options for this instance.
58: * <pre>
59: * - prefix: The module class name prefix.
60: * - dependencies: Constructor argument for CLI modules.
61: * </pre>
62: */
63: public function __construct(array $parameters = null)
64: {
65: if (!isset($parameters['prefix'])) {
66: throw new Horde_Cli_Modular_Exception(
67: 'Missing "prefix" parameter!'
68: );
69: }
70: $this->_prefix = $parameters['prefix'];
71: if (isset($parameters['dependencies'])) {
72: $this->_dependencies = $parameters['dependencies'];
73: }
74: }
75:
76: /**
77: * Return the specified module.
78: *
79: * @param string $module The desired module.
80: *
81: * @return Horde_Cli_Modular_Module The module instance.
82: *
83: * @throws Horde_Cli_Modular_Exception In case the specified module does not
84: * exist.
85: */
86: public function getModule($module)
87: {
88: if (!isset($this->_instances[$module])) {
89: $this->_instances[$module] = $this->createModule($module);
90: }
91: return $this->_instances[$module];
92: }
93:
94: /**
95: * Create the specified module.
96: *
97: * @param string $module The desired module.
98: *
99: * @return Horde_Cli_Modular_Module The module instance.
100: *
101: * @throws Horde_Cli_Modular_Exception In case the specified module does not
102: * exist.
103: */
104: protected function createModule($module)
105: {
106: $class = $this->_prefix . $module;
107: if (!class_exists($class)) {
108: throw new Horde_Cli_Modular_Exception(
109: sprintf('Invalid module %s!', $class)
110: );
111: }
112: return new $class($this->_dependencies);
113: }
114: }