PhpStorm coding tip for Drupal services
Here's a super simple tip to help you work with services for Drupal in PhpStorm (our favourite IDE). First, ensure you have enabled the Drupal Symfony Bridge and Symfony Support plugins; they're brilliant for auto-complete suggestions, and navigating around services, controllers, annotations and twig templates! I find it so helpful to be able to cmd+click (or ctrl+click) on a service name, whether in a YAML definition, or PHP code, and jump straight to the service class. But I'd noticed that PhpStorm often didn't recognise the method used after my code referred to a service like this:
\Drupal::service('my_service') ->something($id);
That meant PhpStorm couldn't give me hints about what parameters the '->something()
' method should take, or even auto-complete what methods are available on the service.
I discovered this is probably because the doxygen for the return type of \Drupal::service()
is simply 'mixed
'. Or perhaps because the Symfony plugin just isn't aware of this Drupalism.
Instead, if I change my code to the following, PhpStorm suddenly understands what the service is, so it can help me code more easily!
\Drupal::getContainer() ->get('my_service') ->something($id);
This is barely any more code, but suddenly I can click into the definition of the ->something()
method, and get all the IDE functionality I normally expect. Win!
Here's how it actually looks for me, demonstrating the inline parameter hint, and with PhpStorm's 'Quick documentation' tooltip opened (press F1 to get this). This is super handy - especially for methods with a ton of parameters!
Of course, this only really matters when you're forced to get the service via the \Drupal
class, rather than dependency injection, such as in static/procedural code. Which might be discouraged, but I doubt will ever be entirely eliminated, especially in custom code which might often be a bit more 'quick & dirty', by necessity.
You could always just add /** @var ... */
doxygen comments around your code to help inform PhpStorm of what a service is. I've seen more and more of that sprinkled around contrib & core code. But I figure this new approach is the simplest to change existing code to, as it's only a very small and less obtrusive change. Plus it allows PhpStorm to dynamically understand your code, rather than you having to teach it. Which allows you to get on with your actual work instead, of writing awesome code.
What do you reckon? Is this a new pattern we should all start using more?