1

I tried to use jasonmapper just as written in manual. I required autoload.php file, and when construct JasonMapper object, I go class not found exception.

(1/1) FatalThrowableError
Class 'App\Http\Controllers\JsonMapper' not found

Here is my code

namespace App\Http\Controllers;

require __dir__.'/../../../vendor/autoload.php';
use Illuminate\Http\Request;
use App\Http\Games\Numbers;

class ApiController extends Controller
{
    public function home()
    {
        $client = new \GuzzleHttp\Client();
        $res = $client->request(
          'GET',
          $testurl
        );
        $json = json_decode($res->getBody());
        $mapper = new JsonMapper();// error occurs at this line
        $numbers = $mapper->map($json, new Numbers());
        return json_encode($numbers);
    }
}
Omi
  • 3,954
  • 5
  • 21
  • 41
ringord
  • 908
  • 3
  • 11
  • 27
  • `new \JsonMapper();` ?? – Brian Gottier Aug 29 '17 at 19:00
  • Possible duplicate of [How does the keyword "use" work in PHP and can I import classes with it?](https://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it) – localheinz Aug 29 '17 at 21:49
  • There's no need to require `vendor/autoload.php` in every class. Require it only in the entry points of your application. – localheinz Aug 29 '17 at 21:51

1 Answers1

2

If you don't "use" JsonMapper at the top of your script, PHP assumes that JsonMapper is in the App\Http\Controllers namespace, which it's not. That means in your script you must:

$mapper = new \JsonMapper();
Brian Gottier
  • 4,522
  • 3
  • 21
  • 37
  • Just tried this, and got "Class 'JsonMapper' not found" error. Adding \ somehow resolve the original error but somehow JsonMapper is still not located. – ringord Aug 29 '17 at 19:12
  • Did you install JsonMapper through Composer? If not, you may have to make changes to your composer.json and then run composer dump-autoload. – Brian Gottier Aug 29 '17 at 20:15