Skip to main content

Namespacing over Use in PHP

I was working on extending a Drupal 8 NodeViewController when I hit a problem that never encounter before:

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

namespace Drupal\mymodule\Controller;

/**
 * @TODO:
 */
class MyNodeController extends NodeViewController {

  // etc...

}
 

After a cache rebuild I was abruptly hit with...

Fatal error: Class 'Drupal\mymodule\Controller\NodeViewController' not found in...

Huh? I defined the namespace for NodeViewController from  Drupal\node\Controller\NodeViewController. Why is it defaulting to my class's namespace? Is something screwing around with the autoloading?

After some other debugging checks, much cache clearing, and a few swear words, I noticed the issue:

use Drupal\node\Controller\NodeViewController;

namespace Drupal\mymodule\Controller;

Without ever noticing the order, of the namespace or use keywords, it turns out this was the essential problem.

As PHP is autoloading classes, defining the namespace after declaring the use of other PHP classes, resets the default used classes somehow, and thus it looked for NodeViewController within the Drupal\mymodule\Controller namespace.

namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * @TODO:
 */
class MyNodeController extends NodeViewController {

  // etc...

}

A quick flip of the order, and a cache reset later, everything was back on track.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
Are you a robot?
Loading Image
Thinking...