I'm writing a module and regardless of what method I choose to implement, xautoload fails to load classes. Here is my situation:

Drupal 7. Third party library using namespaces (psr4) like this...

<?php

namespace xPaw;

class MinecraftQuery {
...

and I'm using the Libraries module. I've tried all (5?) of the different kinds of implementations, from using hook_libraries_info() to hook_xautoload() to hook_init(). I'd like to use the hook_libraries_info() method. Here's my snippet:

function minecraft_query_libraries_info() {

	$libraries['xpaw_php_minecraft_query'] = array(
		'name' => 'xpaw/php-minecraft-query',
		'version' => '1.0',
		'xautoload' => function($adapter) {
			//$adapter->add('xPaw\\', 'src');
			//$adapter->addPsr4('xPaw\\', 'src');
			$adapter->composerJson('composer.json');
		},
	);

	return $libraries;

}

This gives me a class not found exception when I try to use the classes in question (as does every other method). I understand you don't have to call libraries_load(), but I still did before each time I used one of the classes, like...

	if(($library = libraries_load('xpaw_php_minecraft_query')) && !empty($library['loaded'])) {
		$query = new MinecraftQuery();
		... (business stuff)
	else {
		(error stuff)
	}

I've tried everything. I've read about 10 pages of documentation at least twice now. How do I debug this? How can I tell if xautoload is loading my classes, or why it isn't? The library I'm trying to load is stored in "sites/all/libraries/xpaw_php_minecraft_query", and the classes are in "sites/all/libraries/xpaw_php_minecraft_query/src". The code for the library can be found here.

I know Libraries is working because when i use the 'files' key instead of the 'xautoload' key and omit the namespace declarations it loads right up.

Comments

mrmysterious2502 created an issue. See original summary.

mrmysterious2502’s picture

Version: 7.x-5.x-dev » 7.x-5.7
mrmysterious2502’s picture

Status: Active » Closed (works as designed)

Oops. Forgot to add 'xPaw\' before 'MinecraftQuery()'...

...
$query = new xPaw\MinecraftQuery();
...

Sorry. :D

donquixote’s picture

Nice that it works!
It is often these very stupid mistakes that make people lose a lot of time.. sad really.

Btw the usual way to do this is use statements at the top of the file.

use xPaw\MinecraftQuery;

$query = new MinecraftQuery();

Or if you don't want this, I would recommend a fully-qualified class name with leading backslash.

$query = new \xPaw\MinecraftQuery();

A good way to avoid these mistakes, and also to semi-automatically add those use statements, is to use an IDE.

Also the "class not found" error message can give you a clue. If there is really a class loading, then the message should show the full class name including the namespace, in the exactly correct spelling (lowercase/uppercase). If the "class not found" message only says "MinecraftQuery" without the namespace, then it is looking for the wrong class.