Can't get namespacing to work



I have this directory structure for my project:


The index.php is my entry point to the app. In composer I have tried to set up namespacing:

    "autoload": {
        "psr-4": {
            "Bills\\" : "src/"

And then I update composer and try to use namespacing in my index.php:

require_once DIR . ‘/…/vendor/autoload.php’;

use Bills\LoginController;

$actions = explode("/", $_SERVER['REQUEST_URI']);

if($actions[1] != '') {
	$name = ucfirst($actions[1]) . "Controller";
	$object = new $name();


But I always get the error

PHP Fatal error: Uncaught Error: Class 'LoginController' not found

I don’t know how to get namespacing to work here… Any help appreciated


Namespaces can be tricky, but once you get the hang of it then it’s like riding a bicycle. :wink:

My suggestion is to use composer directory structure for the autoload portion of the directory structure.

For example here’s mind:
[php]<?php define(“APP_ROOT”, dirname(dirname(FILE)));
define(“PRIVATE_PATH”, APP_ROOT . “/private”);
define(“PUBLIC_PATH”, APP_ROOT . “/public”);
define(“SMARTY_PATH”, APP_ROOT . “/Smarty”);

require_once PRIVATE_PATH . “/vendor/autoload.php”; /* Composer’s Autoloader */
require_once PRIVATE_PATH . “/security/security.php”;
require_once PRIVATE_PATH . “/throttle/throttle_functions.php”;
require_once PRIVATE_PATH . “/config/config.php”;
require_once PRIVATE_PATH . ‘/pdo_blog/pdo_blog_functions.php’;
require_once SMARTY_PATH . ‘/libs/Smarty.class.php’;[/php]

then src directory is on the SAME level as the vendor directory in my case I call mine Library (Composer psr-4)>
login.php (an example of my login page that’s in the public directory)
require_once ‘…/private/initialize.php’;

use Library\Users\Users;
use Library\FormValidation\FormValidation;
use Library\FormVerification\FormVerification;[/php]

So my file structure is the following

notice my src (Library) directory is on the same level as vendor directory.

A portion of my Users.php file:

namespace Library\Users;

use PDO;
use Library\Database\Database as DB;

//use website_project\database\PDOConnection as PDOConnect;

class Users {

private $connectPDO;
private $pdo;
protected $id = NULL;
protected $query = NULL;
protected $stmt = NULL;
protected $result = NULL;
protected $queryParams = NULL;
protected $row = NULL;
protected $loginStatus = false;
public $user_id = \NULL;
public $user = NULL;
public $userArray = [];
public $username = NULL;

/* Create (Insert) new users information */

public function __construct() {[/php]

Don’t create your own autoloader user composer’s autoloader (though looking over it again it looks like you are using composer’s autoloader), for it will make life easier for you
[php]$ composer dumpautoload -o[/php]

And a real good link that better explains it ->

Read it multiple times and I’m sure you’ll get the drift.

HTH John