4

I have X Autoload installed and enabled. I'm trying to get a simple example to work. The below setup throws the error:

Fatal error: Class 'Pet' not found in MY-SITE/sites/all/modules/foo/foo.module on line 15

Have I got the directory structure correct for pet.php? I'm finding the docs difficult to follow on the placement and naming of the file that contains the class definitions. I'm trying to follow the PSR-0 standard to begin with. Thanks.

UPDATE: The below has now been corrected as per Clive's answer.

foo.info

name = Foo
core = 7.x
dependencies[] = xautoload (>= 7.x-4.0)

foo.module

<?php

function foo_menu() {
  return array(
    'foo' => array(
      'title' => 'Foo',
      'page callback' => 'foo_page',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
    ),
  );
}

function foo_page() {
  $output = \Drupal\foo\Pet::dog();
  return array(
    '#type' => 'markup',
    '#markup' => $output,
  );
}

Pet.php (MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php)

<?php

namespace Drupal\foo;

class Pet {
  public static function dog() {
    return 'Buster';
  }
}
1
  • To address the edit: see the last code block in the answer below. You need to use one of those two methods, currently you're half in-between both
    – Clive
    Apr 14, 2014 at 15:30

1 Answer 1

2

If your file-system is case-sensitive, so is PSR-0. Try changing your class filename to

MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php

And make sure you're namespacing your class correctly, e.g.

namespace Drupal\foo;

class Pet {
  ...
}

Lastly, make sure you're referencing the class correctly in your module file. Either

// Top of file.
use Drupal\foo\Pet;

// In a hook or whatever
$dog = Pet::dog();

or

// In a hook
$dog = \Drupal\foo\Pet::dog();
4
  • Renamed to Pet.php, cleared the cache: same error. Should my class in Pet.php be named: Drupal/foo/Pet rather than just Pet?
    – dbj44
    Apr 14, 2014 at 15:04
  • Yeah, you need the right namespace or what's the point of using PSR-0 ;)
    – Clive
    Apr 14, 2014 at 15:20
  • Working now. Thanks. So, basically this means I don't have to write require "Pet.php"; before I create an object of the class 'Pet'. The method of including a .inc file with all the classes with the module's .info file seems more straight forward. I guess this comes into its own for much bigger projects.
    – dbj44
    Apr 14, 2014 at 15:49
  • Yeah you got it - it can be just as useful in smaller projects I've found
    – Clive
    Apr 14, 2014 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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