1
votes

I have been playing around with Slim 3 and Doctrine but haven't made much progress as I can't for the life of me work out why this isn't working.

Project Structure:

-src
  |-App
    |-index.php
    |-Entity
      |-User.php

  |-vendor

composer.json

{
    "require": {
        "slim/slim": "^3.9",
        "doctrine/orm": "v2.5.9"
    },
    "autoload": {
        "psr-0":{
            "App\\": "src/App"
        }
    }
}

index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use App\Entity\User;

require '../vendor/autoload.php';

$user = new User();

....

But this results in

Fatal error: Class 'App\Entity\User' not found...

I have tried a few variations using psr-4 but still with no success, any help would be greatly appreciated.

Update: User.php

namespace App\Entity;

use App\Entity;
use Doctrine\ORM\Mapping;

/**
 * @Entity
 * @Table(name="users")
 */
class User
{
    /**
     * @var integer
     *
     * @Id
     * @Column(name="id", type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @Column(type="string", length=64)
     */
    protected $name;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }


}
1
It should also be psr-4 and not psr-0. There's a big difference. I would also recommend ending src/App with a slash in your composer file, like this: src/App/ (it will probably work either way, but it's the standard).Magnus Eriksson
Can you please add the User.php? Is the namespace correct, there? Btw @MagnusEriksson the autoloader has to be uncluded before instantiating the first class. So the position is okay after the use. Usages should be the first lines (after namespaces ;-))Demigod
@Demigod - You're correct about the auto loader position. When it comes to use, it doesn't have to be the first lines after the namespace. It's common practice and in most code styles since it make sense, but PHP doesn't enforce it, as long as you have it before you're trying to use any of the imported classes/functions/constants.Magnus Eriksson
Thanks for the replies, I am in the office at the moment, will update question with User contents once I get home.cosmicsafari

1 Answers

0
votes

Adjust your autoloading configuration to use the PSR-4 autoloader instead of the PSR-0 autoloader:

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

For reference, see https://getcomposer.org/doc/04-schema.md#psr-4.