1

I want to autoload class via PHP Composer from file:

<?php
src/Product.php

use Doctrine\ORM\Mapping as ORM;

class product
{

protected $id;


protected $name;


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

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

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

}

to file:

<?php

use Doctrine\ORM\Mapping as ORM;
require_once "bootstrap.php";
require __DIR__ . '/vendor/autoload.php';

$newProductName = $argv[1];

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

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

echo "Created Product with ID " . $product->getId() . "\n";


But I keep geting error:
php create_product.php ORM PHP Fatal error: Uncaught Error: Class 'Product' not found in /home/vaclav/Server/vssk/VSSK/project/create_product.php:9 Stack trace: #0 {main} thrown in /home/vaclav/Server/vssk/VSSK/project/create_product.php on line 9

1 Answer 1

4

You're missing two things:

  1. A namespace in your src/Product.php file. Wrap the whole thing in a namespace for your app (something like MyApp)

  2. Autoloading configured in composer.json:

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

This will map the namespace MyApp to the src folder at the root of your project. Adjust it as needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Also don't forget to run composer dump as 3rd step to rebuild composer cache

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.