TryHarder
TryHarder

Reputation: 2777

Why isn't wordnik's php api loading the required classes?

I'm getting the following error with wordnik's php api Fatal error: Class 'Example' not found in Swagger.php on line 212

I've edited Swagger.php to get it to work, below is the original function

function swagger_autoloader($className) {
    $currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
    if (file_exists($currentDir . '/' . $className . '.php')) {
        include $currentDir . '/' . $className . '.php';
    } elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
        include $currentDir . '/models/' . $className . '.php';
    }
}

The working code I changed to is

function swagger_autoloader($className) 
{
        include $currentDir . '/models/' . $className . '.php'; 
}

MORE INFO

My file structure is as follows. WORDNIK (contains start.php)>>>WORDNIK (contains Swagger.php)>>MODELS (contains Example.php)

UPDATE/EDIT

Using the following code

function swagger_autoloader($className) {
    echo "dirname(__FILE__)= ",dirname(__FILE__);
    $currentDir = substr(__FILE__, 0, strrpos(__FILE__, '/'));
    echo "currentDir=".$currentDir."</br>";
    echo "className=".$className."</br>";
    echo "__FILE__=",__FILE__."<br/>";
    die();

I get the results

As suggested by vcampitelli, using either __DIR__ or dirname(__FILE__) works.

MY QUESTION

Why doesn't the original function work?

UNIMPORTANT INFO

For people struggling through the examples, here is my start.php file

<?php
require('./wordnik/Swagger.php');
require('./wordnik/WordApi.php');
require('./wordnik/AccountApi.php');
require('./wordnik/WordsApi.php');
require('./wordnik/WordListApi.php');
require('./wordnik/WordListsApi.php');

$myAPIKey = 'replace_this_with_your_real_api';
$client = new APIClient($myAPIKey, 'http://api.wordnik.com/v4');

$wordApi = new WordApi($client);
$example = $wordApi->getTopExample('irony');
print $example->text;
?>

Upvotes: 0

Views: 321

Answers (2)

mrjf
mrjf

Reputation: 1137

The original function doesn't work because it is looking for the position of a UNIX-style forward slash '/', whereas you are on Windows and have backslashes '\'. That's a bug! I'll fix the lib to use dirname(FILE) as you do. Thanks for pointing out the error.

Upvotes: 1

vcampitelli
vcampitelli

Reputation: 3252

What does $currentDir return? Have you tried using __DIR__ or dirname(__FILE__) (they are the same) instead of that substr?

If you are using the second example just as you posted (without declaring $currentDir), so that is the problem at your original code: $currentDir is not returning the right folder!

With the original code, which file is being included? Because, actually, I think no one is! Use echo inside those if statements to check that!

Upvotes: 2

Related Questions