@@ -104,3 +104,46 @@ the system up to nanosecond precision. It can be used to measure the elapsed
104
104
time between two calls without being affected by inconsistencies sometimes introduced
105
105
by the system clock, e.g. by updating it. Instead, it consistently increases time,
106
106
making it especially useful for measuring performance.
107
+
108
+ Using a Clock inside a Service
109
+ ------------------------------
110
+
111
+ If your application uses :ref: `service autoconfiguration <services-autoconfigure >`,
112
+ any service whose class uses the :class: `Symfony\\ Component\\ Clock\\ ClockAwareTrait ` will
113
+ benefit of a ``ClockInterface `` typed-property ``$clock `` with the default implementation
114
+ passed as a service. Services using this trait will also benefit of a ``now() `` method.
115
+
116
+ By using this trait in your services to retrieve the current time, it will be easier to
117
+ write time-sensitive classes. For example, by using the ``MockClock `` implementation as the
118
+ default one during tests, you will have full control of the "current time".
119
+
120
+ This is also true for the other clock implementations, as you will be assured to always use
121
+ the same clock implementation across your code each time you need it::
122
+
123
+ namespace App\TimeUtils;
124
+
125
+ use Symfony\Component\Clock\ClockAwareTrait;
126
+
127
+ class MonthSensitive
128
+ {
129
+ use ClockAwareTrait;
130
+
131
+ public function isWinterMonth(): bool
132
+ {
133
+ $now = $this->now();
134
+
135
+ return match ($now->format('F')) {
136
+ 'December', 'January', 'February', 'March' => true,
137
+ default => false,
138
+ };
139
+ }
140
+ }
141
+
142
+ Thanks to the ``ClockAwareTrait `` and by using the ``MockClock `` implementation,
143
+ you will be able to test different times returned by ``now() ``. This allows you
144
+ to test every case of your method without the need of actually being in a month
145
+ or another.
146
+
147
+ .. versionadded :: 6.3
148
+
149
+ The :class: `Symfony\\ Component\\ Clock\\ ClockAwareTrait ` was introduced in Symfony 6.3.
0 commit comments