2

This may be obvious to expert D8 users, but; If I am implementing hook_form_alter in Drupal 8, the hook definition looks like this:

hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

In that there is a direct reference to FormStateInterface, so am I right in saying that it is redundant to also have the use statement in my file:

use Drupal\Core\Form\FormStateInterface; // Still works if I comment this out

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  ...
}

When generating the code using Drupal Console I get:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ...
}

Best practice? It seems neater to me that the hook itself references FormStateInterface, making the use statement redundant.

1

It is recommended to use the use + short reference. Technically, it makes no difference, but it results in shorter lines and is easier to read.

The reason the hook documentation always uses full namespace is to make it easier to copy it into a module file, as you'd otherwise also have to look up the use statement.

1
  • Thanks, I figured that was probably the case. Having the hooks documentation with full namespace references is essential. – Duncanmoo Oct 24 '16 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.