SelfDecode Support SelfDecode Support - 6 days ago 7
PHP Question

PHP - Doctrine - How to autoload entities classes using a single namespace

I have a group of PHP files containing classes (entities). Each class has the same namespace:

// src/App/Entity/Actions.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* Actions
*
* @ORM\Entity
*/
class Actions
{
// SOME CODE


I autoload the PHP files containing the classes with composer:


"autoload": {
"psr-0": {
"App": "src/"
}
}



And in my bootstrap.php file, I add this line:

use App\Entity;


So I figured that because told the app to use the App\Entity namespace, that I can just call the entity classes like this:
$entity = new Actions();


but when I try that, I get this error:


Fatal error: Class 'Actions' not found in C:\wamp64\www\spider\chebi2\inc\orm_tools.php on line 49


If I do this:

use App\Entity; use App\Repository;

if (class_exists('Actions')) { dump('exists'); } else { dump('not exists'); }

if (class_exists('\App\Entity\Actions')) { dump('exists'); } else { dump('not exists'); }


Heres what it outputs:

PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"


So it can only find the class when I provide the full namespace. And weirdly enough, when I tried this:

// Direct path to the Actions.php file
use App\Entity\Actions;

if (class_exists('Actions')) { dump('exists'); }
else { dump('not exists'); }

if (class_exists('\App\Entity\Actions')) { dump('exists'); }
else { dump('not exists'); }


I get the same result:

PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"


So now I'm even more confused. What is the point in using:
use App\Entity;
if it doesn't actually make the classes in that namespace directly available? And why is assigning the direct path to the class
use App\Entity\Actions;
not even working?

Am I doing something wrong here? Is there a correct way to use namespaces that I'm not understanding?

Answer

PSR-0 is depracated you should use PSR-4

in PSR-4

composer.json

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

in directory src/ which is on same level as composer.json add directory Entity so in path src/Entity add class file Actions

namespace App\Entity;

class Actions
{

}

you can also use composer dump-autoload and check vendor/composer/autoload* fiels and see if namespaces are registered there.'

Regarding class_exists() it does not work with short names or aliases you need to provide the full name of class. I'd suggest using ::class operator So in your case it would be:

<?php
  use App\Entity\Actions;

  class_exists(Actions::class);
Comments