简体   繁体   中英

Doctrine Entity “Class not found”

I'm proceeding to Doctrine's Getting Started guide and stuck in the beginning because of "Class 'Product' not found in /var/www/test/product-create.php on line 6":

<?php
require_once 'bootstrap.php';

$newProductName = $argv[1];

>>>>> $product = new Product();
$product->setName($newProductName);

$entityManager->persist($product);
$entityManager->flush();

echo sprintf('Created Product with ID %d' . PHP_EOL, $product->getId());

As written in guide, I have the Product class under "./src" directory in my project.

Please, help me, because I want to start using Doctrine without Symfony and I can't move any further.

Here is my bootstrap.php:

<?php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

use Symfony\Component\Yaml\Parser;

require 'vendor/autoload.php';

$yaml = new Parser();

$parameters = $yaml->parse(file_get_contents(__DIR__ . '/parameters.yml'));
$parameters = $parameters['parameters'];

$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . '/src'), $parameters['debug']);

$conn = array
    (
        'host'      => $parameters['database_host'],
        'port'      => $parameters['database_port'],
        'driver'    => $parameters['database_driver'],
        'user'      => $parameters['database_user'],
        'password'  => $parameters['database_password'],
        'dbname'    => $parameters['database_name']
    );

$entityManager = EntityManager::create($conn, $config);

And this is my Product.php:

<?php
/**
 * @Entity
 * @Table (name="products")
 **/
class Product
{
    /**
     * @Id
     * @Column(type="integer") @GeneratedValue
     **/
    protected $id;

    /**
     * @Column(type="string")
     **/
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Thank you all in advance!

I dont see where you include Product class. You need to write in the top of your file

require_once 'patch_to_your_class/Product.php';

or to use an autoloader for classes.

I just came across your question now, and hope that you found an answer, but to help others you need to make sure that you included in your composer.json the following

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

Or include it manually like @Сергей Студеникин suggested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM