I have a service class declared like this:
class MyService implements MyServiceInterface {
I want to get rid of a (working) call to a the static \Drupal::service('date.formatter')
function and replace with a injected call to $this->dateFormatter
.
I am looking at the most upvoted answer to this question: Make a custom date formatter for view.
It suggests that you can output a custom formatted timestamp like this:
$now = \Drupal::time()->getCurrentTime();
$currenttime = $this->dateFormatter->format($now, 'custom', 'Y-m-d H:i');
However, this does not work for me. It uses an injected call to the public function DateFormatter::format, and the upvoted answer does not explain how to set up the class where it is used to inject this service. This produces a WSOD on my site. The cause is obviously that dateFormatter
has not been initialized.
As noted, I know that using a static call works:
$now = \Drupal::time()->getCurrentTime();
$currenttime = \Drupal::service('date.formatter')->format($now, 'custom', 'Y-m-d H:i');
I have a rough idea bout how to set up a service class to initialize an injected service. I.e. I think to be able to use it, I need to do at least three things:
- Declare the injected service as an argument in
myservice.services.yml
. - Declare the injected property as a
$protected
variable. - Initialize it in the class' contructor.
But I am not even sure if this is correct. And the details eludes me. For example: How do I discover what name to include in myservice.services.yml
?
Any guidance will be appreciated.
PS: I have studied this answer: How do I inject services in a service, but I don't understand how it applies to my question.
It has been suggested that Inject a class as dependecy injection in a service is a duplicate. The accepted answer to that question is not about the @date.formatter
service that is the subject of my question, and it does not mention using autowire
to solve the problem. (Which I learned how to use in the answer I now have accepted.)
@date.formatter
service, so there is no need to create a factory for it. It is an answer for a different use case.