Reputation: 1143
I've been trying to get psr-4 autoloading work for over a week now with no success.
My file structure is as follows:
-Project
-src
-classes
session.php
-vendor
index.php
I've created the psr-4 autoload function as follows:
"autoload": {
"psr-4": {
"classes\\": "src/classes"
}
}
after using composer dump-autoload -0 ,inside my session.php class I gave the namespace:
namespace classes;
class session{
public static function exist($name){
return(isset($_SESSION[$name])) ? true : false;
}
I then required the autoloader and used the use function to name the session class as follows:
use src\classes\session as session;
require_once('vendor/autoload.php');
session::put('test', 'test');
after opening up the index.php page, I get a
Fatal error: Class 'src\classes\session' not found in /var/www/test/Project/index.php on line 10
is my directory structure / php correct? I've tried many different guides online and can't seem to get it to work.
Upvotes: 0
Views: 1187
Reputation: 9592
Most simple solution:
use classes\session;
require_once('vendor/autoload.php');
session::put('test', 'test');
However, you probably don't want to use classes
as a vendor namespace, but instead adjust a few things here and there:
-Project
-src
Session.php
-public
index.php
-vendor
composer.json
{
"autoload": {
"psr-4": {
"Juakali\\": "src"
}
}
}
Replace Juakali
with a vendor namespace you prefer, this is just a suggestion. Ideally, if you intend to publish your package, it should be one that isn't already claimed by someone else, see https://packagist.org.
For reference, see
Juakali\Session
Use the aforementioned vendor namespace of your choice:
namespace Juakali;
class Session
{
public static function exist($name)
{
return isset($_SESSION[$name]);
}
}
Consider using a widely used coding style, for example PSR-2.
For reference, see
index.php
Assuming that you want to expose index.php
as the entry point for a web application, move it into a directory which you feel confident to expose as a document root of your web server, adjust the import in index.php
, as well as the path to vendor/autoload.php
:
use Juakali\Session;
require_once __DIR__ . '/../vendor/autoload.php';
Session::put('test', 'test');
Upvotes: 3
Reputation: 6871
It looks like you're defining your alias of "src/classes" as 'classes'. So you need to use:
use classes\session;
Instead
More info: PSR-4 autoloader Fatal error: Class not found
Upvotes: 0