Dmitry Ermichev
Dmitry Ermichev

Reputation: 423

Yii2 preferred way to set 'class'

In Yii2 codebase, I saw 2 different types of config declaration:

One way with CLASS_NAME::class

'options' => ['class' => OptionsAction::class],

Another way with full string representation

'options' => ['class' => 'yii\rest\OptionsAction'],

Which way is preferable and why?

Upvotes: 3

Views: 59

Answers (1)

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

Both ways might be used, but the better way is the declaration with help ::class because:

  • it makes dependencies more clear. All dependencies will declare one place - in USE section.
  • it makes an ability to validation of code with help IDE. If there is a class name in a string then IDE can't analyze this string and it means IDE can't validate your code
  • it makes refactoring of existing code more usability. If all dependencies will declare in one place and they won't be contained in strings you won't look for a necessary declaration of a class name in all code and you can apply tools of your IDE to code refactoring

Upvotes: 2

Related Questions