1 | <?php |
||
26 | abstract class AbstractHelper |
||
27 | { |
||
28 | /** |
||
29 | * @var XoopsModule |
||
30 | */ |
||
31 | protected $module; |
||
32 | |||
33 | /** |
||
34 | * @var bool true if debug is enabled |
||
35 | */ |
||
36 | protected $debug; |
||
37 | |||
38 | /** |
||
39 | * Instantiate a XoopsModule object for the helper to use. |
||
40 | * The module is determined as follows: |
||
41 | * - if null is passed, use the current module |
||
42 | * - if a string is passed, use as dirname to load |
||
43 | * |
||
44 | * @param string|null $dirname dirname |
||
45 | */ |
||
46 | 2 | public function __construct($dirname = null) |
|
|
|||
47 | { |
||
48 | 2 | $this->module = null; |
|
49 | 2 | if (class_exists('Xoops', false)) { |
|
50 | 2 | $xoops = \Xoops::getInstance(); |
|
51 | } |
||
52 | 2 | if (empty($dirname)) { |
|
53 | // nothing specified, use current module |
||
54 | // check if we are running in 2.6 |
||
55 | 2 | if (isset($xoops)) { |
|
56 | 2 | if ($xoops->isModule()) { |
|
57 | 2 | $this->module = $xoops->module; |
|
58 | } |
||
59 | } else { |
||
60 | 2 | $this->module = $GLOBALS['xoopsModule']; |
|
61 | } |
||
62 | } else { |
||
63 | // assume dirname specified, try to get a module object |
||
64 | if (isset($xoops)) { |
||
65 | $moduleHandler = $xoops->getHandlerModule(); |
||
66 | } else { |
||
67 | $moduleHandler = xoops_getHandler('module'); |
||
68 | } |
||
69 | $this->module = $moduleHandler->getByDirname($dirname); |
||
70 | } |
||
71 | 2 | if (is_object($this->module)) { |
|
72 | $this->init(); |
||
73 | } |
||
74 | 2 | } |
|
75 | |||
76 | /** |
||
77 | * init() is called once/if __construct has a module object. |
||
78 | * $this->module will have a module object that any further |
||
79 | * initialization can use. |
||
80 | * |
||
81 | * @return void |
||
82 | */ |
||
83 | abstract public function init(); |
||
84 | |||
85 | /** |
||
86 | * Set debug option on or off |
||
87 | * |
||
88 | * @param bool $bool true to turn on debug logging, false for off |
||
89 | * |
||
90 | * @return void |
||
91 | */ |
||
92 | 1 | public function setDebug($bool = true) |
|
96 | |||
97 | /** |
||
98 | * Add a message to the module log |
||
99 | * |
||
100 | * @param string $log log message |
||
101 | * |
||
102 | * @return void |
||
103 | */ |
||
104 | 1 | public function addLog($log) |
|
110 | } |
||
111 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: