1

我一直在关注一些让 Doctrine 运行的教程,当我尝试将对象插入数据库时​​似乎挂断了。作为参考,这就是我所关注的:教义2教程

  • Doctrine 安装在 application/libraries 文件夹中
  • Doctrine.php 引导程序位于 application/libraries 文件夹中
  • 在 application/ 文件夹中创建一个 cli.php 文件
  • 教程没有说我的第一个实体模型放在哪里,所以我把它放在应用程序/模型中

命名空间实体;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="user")
 */
class User
{

/**
 * @Id
 * @Column(type="integer", nullable=false)
 * @GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @Column(type="string", length=32, unique=true, nullable=false)
 */
protected $username;

/**
 * @Column(type="string", length=64, nullable=false)
 */
protected $password;

/**
 * @Column(type="string", length=255, unique=true, nullable=false)
 */
protected $email;

/**
 * The @JoinColumn is not necessary in this example. When you do not specify
 * a @JoinColumn annotation, Doctrine will intelligently determine the join
 * column based on the entity class name and primary key.
 *
 * @ManyToOne(targetEntity="Group")
 * @JoinColumn(name="group_id", referencedColumnName="id")
 */
protected $group;

}

/**
 * @Entity
 * @Table(name="group")
 */
class Group
{

/**
 * @Id
 * @Column(type="integer", nullable=false)
 * @GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @Column(type="string", length=32, unique=true, nullable=false)
 */
protected $name;

/**
 * @OneToMany(targetEntity="User", mappedBy="group")
 */
protected $users;

}
  • 在数据库中创建我的架构没有问题:php cli.php orm:schema-tool:create
  • 得到“使用原则”设置下的最后一步
  • 尝试在我的控制器中使用以下代码,但出现错误

    $em = $this->doctrine->em;
    
    $user = new models\User;
    $user->setUsername('Joseph');
    $user->setPassword('secretPassw0rd');
    $user->setEmail('josephatwildlyinaccuratedotcom');
    
    $em->persist($user);
    $em->flush();
    

生产

Fatal error: Class 'models\User' not found in C:\wamp\www\ci\application\controllers\Home.php on line 11

我唯一的想法是路径可能有问题,因为我在 Windows 中,或者我将实体模型放在错误的位置。

4

1 回答 1

1

您正在关注的教程中,有一个重要的设置:

// With this configuration, your model files need to be in
// application/models/Entity
// e.g. Creating a new Entity\User loads the class from
// application/models/Entity/User.php
$models_namespace = 'Entity';

这是您的 Doctrine 实体(模型)必须使用的命名空间,看起来您正在正确地使用它namespace Entity;作为模型的第一行。您可以将其设置为任何您想要的。

使用此配置,您的模型文件需要在application/models/Entity

创建实体实例时,请使用您配置的命名空间 - 而不是模型路径:

// $user = new models\User; "models" is not the right namespace
$user = new Entity\User;
于 2012-12-27T17:03:50.740 回答