Tims
Tims

Reputation: 651

php json-schema - Fatal Error: Class not found

New to PHP!

I have /var/www/html/index.php requiring json-schema from https://github.com/justinrainbow/json-schema

downloaded from git and moved JsonSchema folder to /var/www/html

the following in index.php gives Fatal error: Class 'JsonSchema\Constraints\Constraint' not found

require "JsonSchema/Validator.php";
use JsonSchema\Validator;
$validator = new JsonSchema\Validator();
$validator->check(json_decode($data), json_decode($schema));

if I include Constraint.php, it throws out another error. am missing some basics here. what is the proper way to use an external library?

thanks!

Upvotes: 2

Views: 2970

Answers (1)

Jeff Puckett
Jeff Puckett

Reputation: 41011

If you look in the project root, then there's a special file called composer.json wherein you will find on line 46 the namespace autoloader.

"autoload": {
    "psr-4": { "JsonSchema\\": "src/JsonSchema/" }
},

When you install your project with composer, then this will generate a file called autoload.php which once included in your script will allow you to access all of the classes. Otherwise you are doomed to requiring each class one by one.

Furthermore, requiring each class is really inefficient on memory usage and runtime, so composer's autoload.php uses spl_autoload_register which is even better because it only loads the classes when they're actually called. Otherwise if you require a ton of classes and don't use all of them, then it's just a waste of resources and slows things down.

First thing you will need is composer

wget http://getcomposer.org/composer.phar

Usually people will use composer for downloading and including packages like this one as a new project dependency.

php composer.phar require justinrainbow/json-schema:~2.0

But since you've already cloned the source code because you want to actually develop this package, then you can simply generate the autoloader with:

php composer.phar dump-autoload

So your script should look like this:

require __DIR__ . '/vendor/autoload.php';

use JsonSchema\Validator;
$validator = new JsonSchema\Validator();
$validator->check(json_decode($data), json_decode($schema));

Upvotes: 5

Related Questions