1

I have a very simple Drupal 7 module in which I want to load a custom class. I'm not able to load the class and I get the following error when I enable the module:

Fatal error: Class 'Drupal\testmodule\TestClass' not found in www/sites/all/modules/testmodule/testmodule.module on line 4

Here are the contents of my module files:

testmodule.info

name = "Test Module"
core = 7.x
files[] = src/TestClass.php

testmodule.module

<?php

function testmodule_init() {
  Drupal\testmodule\TestClass::go();
}

src/TestClass.php

<?php

namespace Drupal\testmodule;

class TestClass {
  function go() {
    print 'Foo!';
  } 
}

Please could anyone help me understand why Drupal 7's dynamic-loading code registry is not working as documented here: https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#files ?

2

To use namespaced classes in Drupal 7, you can use one of these modules:

One reason for choosing one or the other may be if you have other modules that also depend on one of those modules.

Otherwise I guess it is largely a matter of taste.

One difference is that xautoload is more convenient during development, because newly created PSR-4 classes are immediately available without rebuilding the class registry.

On the other hand, it does a lot of things which you probably don't need right now, and the code looks complex.

Of course you could do some profiling to find out which is faster, but as always you would need to be careful what you measure and what you compare. I currently cannot tell you which one is faster, or better for memory.

There is also the alternatives module that can help to have only one of those enabled, instead of both.

Disclaimer: I am the author of one of these modules, and I am subscribed to the autoload tag on drupal.stackexchange.com.

0

I believe the reason is that Drupal 7's class loader doesn't account for namespaces, so it would find \TestClass but \Drupal\testmodule\TestClass is not found.

There are two ways around this: don't use namespaces (may not be possible), or include your own class loader as one of the files mentioned in your .info file.

There are examples of trivial autoloaders on this page: http://php.net/manual/en/language.oop5.autoload.php

  • Thank you @rivimey. Removing the namespaces does indeed work. I removed the namespace line from src/TestClass.php and called the go() method in testmodule.module with just TestClass::go(); I've realised this is a duplicate of [drupal.stackexchange.com/questions/60830/… issue) – eddie_c Jul 13 '17 at 10:58

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.