osantos
osantos

Reputation: 414

PHP Class not being autoloaded by composer or at leas it is not found

I am starting a lumen project and I am facing an issue with namespaces and autoload. In my composer.json file in the project root directory it states the following:

   "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },

In the root dirctory we have the following directory structure (among others):

./app/
   ->  Common/TokenFactory.php
   ->  Http/
       ->   Controllers/UserController.php

TokenFactory.php contains the following very simple code:

<? php
namespace App\Common;

class TokenFactory
{
    public function generateToken($tokenLength = 40)
    {
        $length_div = round($tokenLength/2, 0, PHP_ROUND_HALF_DOWN);
        return bin2hex(openssl_random_pseudo_bytes($length_div));
    }
}

?>

I wish to use this class in the UserController.php file where I have the following code:

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use App\Common\TokenFactory;

class UserController extends Controller
{
 .............

But when I try to instantiate a TokenFactory in the UserController class I get the error:

Class 'App\Common\TokenFactory' Not foud.

what am I doing wrong? I have created the Common direcotry myself but My undestanding is that Autoloader should be able to use the namespace defines to locate an load the file as needed. I have been struggling with this for quite some time now, any suggestions will be appreciated.

ADDITIONAL NOTE: I have noticed that when calling the service, although I get the message that the class was not found, the contents of the file are shown in the error message, meaning that somehow it is locating and loading the file but not recognizing the class when calling it in the file where the use clause is used. See image bellow.ARC Screen Capture

Upvotes: 0

Views: 222

Answers (2)

gview
gview

Reputation: 15361

We found that in this case a small typo was the culprit. Unfortunately this happens from time to time. I will say that command line php does have a syntax checker/linter that can be of aid, if your editor or IDE misses something like this.

php -l myscript.php

It has helped me out a few times in the past.

In this case the issue was:

<? php
namespace App\Common;

class TokenFactory
{

The beginning tag needs to be <?php

Upvotes: 1

gth44
gth44

Reputation: 87

First of all, I would remove the closing PHP-Tag "?>" at the end of the TokenFactory.

After that I'd suggest to require the TokenFactory-File per hand in your controller: Does it work if you do this?

Upvotes: 0

Related Questions