Reputation: 935
I'm having a problem with using autoloaded classes through composer.
Here is my file structure:
-cache
-public
-src
--Repository
---PostRepository.php
-index.php
-composer.json
I'm trying to load PostRepository.php in index.php. But getting an error
Fatal error: Uncaught Error: Class 'App\Repository\PostRepository' not found in /opt/lampp/htdocs/index.php:12 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/index.php on line 12
Here is my composer.json:
{
"require": {
"twig/twig": "^2.0"
},
"autoload": {
"psr-4": {
"App\\" : "src/"
}
}
}
here is my PostRepository.php
<?php
namespace App\Repository;
class PostRepository
{
...
}
and here is my index.php
<?php
require __DIR__ . "/vendor/autoload.php";
use App\Repository\PostRepository;
$postClass = new PostRepository();
$posts = $postClass->getAllPosts();
var_dump($posts);
It looks like namespaces are ok. What could be wrong?
Upvotes: 1
Views: 5741
Reputation: 2022
you should include the autoload.php before using any class.
try to make your code like this:
<?php
require __DIR__ . "/vendor/autoload.php";
use App\Repository\PostRepository;
$postClass = new PostRepository();
$posts = $postClass->getAllPosts();
var_dump($posts);
then do
composer dump-autoload
Fatal error: Uncaught Error: Class 'App\Repository\PostRepository' not found in /opt/lampp/htdocs/index.php:12 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/index.php on line 12
htdocs/index.php !! do you have one project in htdocs?
because you should be referencing htdocs/your-project-folder/index.php
Upvotes: 3