编程语言
首页 > 编程语言> > php-原理,名称空间和自动加载实体

php-原理,名称空间和自动加载实体

作者:互联网

我想在我的项目中使用Doctrine 2.我有一些问题.我阅读了文档,但可能我做错了.

我想自动加载实体类.而且文档中的方法不起作用.

我的bootstrap.php

<?php

require_once "vendor/autoload.php";
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver;

$paths = array("../Entities");
$isDevMode = false;

$classLoader = new \Doctrine\Common\ClassLoader('Entities','../Entities');
$classLoader->register();

// the connection configuration
$dbParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'xxx',
    'password' => 'xxx',
    'dbname'   => 'xxx',
);

$driver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(new Doctrine\Common\Annotations\AnnotationReader(),array('../Entities'));
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$config->setMetadataDriverImpl($driver);
$em = EntityManager::create($dbParams, $config);

我在Entities目录中有模型的类.我已经使用教义客户端生成了它们.他们看起来还可以.开头有id,setter,getter和名称空间.

/Entities/ArticleCat.php

<?php

namespace Entities;

use Doctrine\ORM\Mapping as ORM;

/**
 * ArticleCat
 *
 * @ORM\Table(name="article_cat")
 * @ORM\Entity
 */
class ArticleCat
{

我要使用主义的脚本:

<?php
  require_once 'bootstrap.php';

  $article = $em->find('ArticleCat', 21);
  echo $article->getName();

没用只有当我以这种方式使用它并从实体模型中删除名称空间时,它才有效.

<?php
  require_once 'bootstrap.php';
  require_once 'Entities/ArticleCat.php'; //this line added (manual load)


  $article = $em->find('ArticleCat', 21);
  echo $article->getName();

使用学说和自动加载实体的正确方法是什么?为什么命名空间有问题?

我的错误:

Fatal error: Uncaught exception 'Doctrine\Common\Persistence\Mapping\MappingException' 
with message 'Class 'ArticleCat' does not exist' in 
/myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:96
Stack trace: #0 /myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php(40): 
Doctrine\Common\Persistence\Mapping\MappingException::nonExistingClass('ArticleCat') 
#1 /myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping
   /AbstractClassMetadataFactory.php(267): Doctrine\Common\Persistence\Mapping
   \RuntimeReflectionService->getParentClasses('ArticleCat') 
#2 /myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping
   /AbstractClassMetadataFactory.php(297): Doctrine\Common\Persistence\Mapping
   \AbstractClassMetadataFactory->getParentClasses('ArticleCat') 
#3 /myproject/vendor/doc in /myproject/vendor/doctrine/common/lib/Doctrine/Common/Persistence
   /Mapping/MappingException.php on line 96

解决方法:

尝试对名称空间使用完全限定的类名.
当您遇到关于CG代理类的错误时,请尝试通过运行生成代理类

vendor/bin/doctrine orm:generate-proxies

祝好运!

标签:doctrine-orm,autoload,doctrine,namespaces,php
来源: https://codeday.me/bug/20191122/2061553.html