Using \Drupal::anything in OO code is not a good idea, mostly because it means you aren't properly injecting your dependencies.

There should be at least a warning for this.

Comments

cweagans created an issue. See original summary.

  • klausi committed 26b74c2 on 8.x-2.x
    Issue #2608738: Add a warning for \Drupal:: use in forms and controllers
    
klausi’s picture

Pushed a first version of this to throw warnings in classes that extend FormBase or ControllerBase. Further suggestions welcome!

dawehner’s picture

It is interesting, because for me, the codesmell is mainly when its part of generic services, rather the controllers / forms, which are integration level code anyway.

martin107’s picture

Regrettably I think \Drupal::anything is going to be with us for a while.

Maybe a movement/attitude like the the one I am linking to.

Slowly we can beat the practice out of core.

Anyway just a suggestion.

  • klausi committed 0c9c097 on 8.x-2.x
    Issue #2608738: Added BlockBase as extending class where dependency...
klausi’s picture

  • klausi committed e935e29 on 8.x-2.x
    Issue #2608738: Add EntityForm as parent class where dependency...
mile23’s picture

+1 on this idea. I doubt it will be in core's phpcs.xml.dist file any time soon, however. :-)

dawehner’s picture

Nice!

Yeah I'm truely convinced that everytime you have to use \Drupal you have some sort of design flaw.
Random example: Entity classes should not contain logic, so often this logic should be totally separate and just change the entity object for example.

mile23’s picture

Yeah I'm truely convinced that everytime you have to use \Drupal you have some sort of design flaw.

:-)

klausi’s picture

Status: Active » Fixed

I think we can call this fixed now. The sniff only reports on a subset of classes, but it is good enough as a start.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.