我想通过 PHP Composer 从文件自动加载类:
<?php
src/Product.php
use DoctrineORMMapping 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;
}
}
到文件:
<?php
use DoctrineORMMapping 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";
但是我不断收到错误:
PHP create_product.php ORMPHP 致命错误:未捕获错误:在/home/vaclav/Server/vssk/VSSK/project/create_product.php:9 中找不到类"产品"堆栈跟踪:#0 {主} 在第 9 行放入/home/vaclav/Server/vssk/VSSK/project/create_product.php
你错过了两件事:
-
src/产品.php文件中的
namespace
。将整个内容包装在应用程序的命名空间中(类似于MyApp
( -
composer.json
中配置的自动加载:"autoload": { "psr-4": { "MyApp\": "src/" } }
这会将命名空间MyApp
映射到项目根目录下的 src 文件夹。根据需要进行调整。