You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit e6a23c0
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: docs/concepts/services.md
+27-10Lines changed: 27 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -15,7 +15,9 @@ A quick example will probably make things clearer, so imagine that you need to p
15
15
```php
16
16
<?php
17
17
18
-
$timer = new \CodeIgniter\Debug\Timer();
18
+
use CodeIgniter\Debug\Timer;
19
+
20
+
$timer = new Timer();
19
21
```
20
22
21
23
And this works great, until you decide that you want to use a different timer class in its place. Maybe this one has some advanced reporting that the default timer does not provide. In order to do this, you now have to locate all of the places in your application where you have used the timer class. Since you might have left them in place to keep a performance log of your application constantly running, this might be a time-consuming and error-prone way to handle this. That's where services come in handy.
@@ -25,10 +27,12 @@ Instead of creating the instance ourselves, we let a central class create an ins
25
27
```php
26
28
<?php
27
29
30
+
use Config\Services;
31
+
28
32
$timer = service('timer');
29
33
30
34
// The code above is the same as the code below.
31
-
$timer = \Config\Services::timer();
35
+
$timer = Services::timer();
32
36
```
33
37
34
38
When you need to change the implementation used, you can modify the services configuration file, and the change happens automatically throughout your application without you having to do anything. Now you just need to take advantage of any new functionality and you're good to go. Very simple and error-resistant.
@@ -77,7 +81,9 @@ If you want to get a new instance of the Timer class, you need to pass `false` t
77
81
```php
78
82
<?php
79
83
80
-
$timer = \Config\Services::timer(false);
84
+
use Config\Services;
85
+
86
+
$timer = Services::timer(false);
81
87
```
82
88
83
89
### Convenience Functions
@@ -91,10 +97,12 @@ The first is `service()`, which provides access to the requested service. The on
91
97
```php
92
98
<?php
93
99
100
+
use Config\Services;
101
+
94
102
$logger = service('logger');
95
103
96
104
// The code above is the same as the code below.
97
-
$logger = \Config\Services::logger();
105
+
$logger = Services::logger();
98
106
```
99
107
100
108
!!! note "Note"
@@ -107,10 +115,12 @@ If the creation method requires additional parameters, they can be passed after
0 commit comments