Skip to content

Commit 2ae947c

Browse files
committed
Auto-discover events
1 parent b35a618 commit 2ae947c

2 files changed

Lines changed: 27 additions & 21 deletions

File tree

application/Config/Modules.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class Modules
1414
*/
1515
public $enabled = [
1616
'events',
17+
'helpers',
1718
'registrars',
1819
'routes',
1920
'services',
@@ -38,6 +39,7 @@ class Modules
3839
*
3940
* Valid values are:
4041
* - events
42+
* - helpers
4143
* - registrars
4244
* - routes
4345
* - services

system/Events/Events.php

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php namespace CodeIgniter\Events;
22

3+
use Config\Services;
4+
35
/**
46
* CodeIgniter
57
*
@@ -53,19 +55,12 @@ class Events
5355
protected static $listeners = [];
5456

5557
/**
56-
* Flag to let us know if we've read from the Config file
58+
* Flag to let us know if we've read from the Config file(s)
5759
* and have all of the defined events.
5860
*
5961
* @var bool
6062
*/
61-
protected static $haveReadFromFile = false;
62-
63-
/**
64-
* The path to the file containing the events to load in.
65-
*
66-
* @var string
67-
*/
68-
protected static $eventsFile = '';
63+
protected static $initialized = false;
6964

7065
/**
7166
* If true, events will not actually be fired.
@@ -92,18 +87,33 @@ class Events
9287
public static function initialize(string $file = null)
9388
{
9489
// Don't overwrite anything....
95-
if ( ! empty(self::$eventsFile))
90+
if (self::$initialized)
91+
{
92+
return;
93+
}
94+
95+
$config = config('Modules');
96+
97+
if (! $config->shouldDiscover('events'))
9698
{
9799
return;
98100
}
99101

100-
// Default value
101-
if (empty($file))
102+
$locator = Services::locator();
103+
104+
$files = $locator->search('Config/Events.php');
105+
106+
foreach ($files as $file)
102107
{
103-
$file = APPPATH . 'Config/Events.php';
108+
if (! file_exists($file))
109+
{
110+
continue;
111+
}
112+
113+
include $file;
104114
}
105115

106-
self::$eventsFile = $file;
116+
self::$initialized = true;
107117
}
108118

109119
//--------------------------------------------------------------------
@@ -155,15 +165,9 @@ public static function on($event_name, callable $callback, $priority = EVENT_PRI
155165
public static function trigger($eventName, ...$arguments): bool
156166
{
157167
// Read in our Config/events file so that we have them all!
158-
if ( ! self::$haveReadFromFile)
168+
if ( ! self::$initialized)
159169
{
160170
self::initialize();
161-
162-
if (is_file(self::$eventsFile))
163-
{
164-
include self::$eventsFile;
165-
}
166-
self::$haveReadFromFile = true;
167171
}
168172

169173
$listeners = self::listeners($eventName);

0 commit comments

Comments
 (0)