php - Doctrine2 自动生成类中的自定义函数

标签 php codeigniter doctrine-orm

有没有办法扩展 Doctrine2 从数据库自动生成的类?

示例:我有这个由 Doctrine 生成的 User 类。

<?php

namespace Entities;

/**
 * User
 */
class User
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $firstName;

    /**
     * @var string
     */
    private $lastName;


    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

我想添加这个功能:

public function getFullName()
{
    return $this->getFirstName().' '.$this->getLastname();
}

有没有比直接将其添加到此类中更简洁的方法?

我尝试在库中创建另一个类(测试)并扩展它,然后将其添加到自动加载(正在运行)中,但是当我尝试保存对象时出现错误:

class Test extends Entities\User {
    public function getFullName() {
        return $this->getFirstName().' '.$this->getLastname();
    }
}

Message: No mapping file found named 'Test.dcm.yml' for class 'Test'.

我在 CodeIgniter3 中使用 Doctrine2。

谢谢。

最佳答案

Doctrine 2 FAQ 中所述:

The EntityGenerator is not a full fledged code-generator that solves all tasks. [...] The EntityGenerator is supposed to kick-start you, but not towards 100%.

用简单的英语来说,这意味着你要求 Doctrine 只生成一次实体文件。之后,您就可以自己对它们进行任何您喜欢(或需要)的更改。

因为实体不仅是某些属性的容器,而且是整个 Action 发生的地方,这就是流程应该发生的方式,Doctrine 无法为您编写更多代码。

向 Doctrine 生成的 stub 实体添加功能的唯一方法是通过编写代码来完成生成的类,该代码根据每个实体在您的域模型中的角色实现其功能。

关于另一个问题,在 Test 类上,错误消息是不言自明的:任何传递给 EntityManager 进行处理的类都需要映射。

查看有关 Inheritance Mapping 的帮助页面.您可以将类 User 映射为 Mapped Superclass (它就像派生类的模板,它的实例不保存在数据库中)或者你可以使用 Single Table Inheritance将从 User 派生的所有类的实例存储在一个表中(当它们具有相同的属性但不同的行为时很有用)。

或者,如果你创建类 Test 只是因为你害怕修改 Doctrine 生成的代码,将你需要的行为放在类 User 中并删除类 测试

关于php - Doctrine2 自动生成类中的自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29410873/

相关文章:

symfony - 在我的代码中触发 Doctrine 生命周期事件

php - CakePHP 3 - 有条件地为关联表创建新实体

PHP - PDO 参数编号无效

php - Codeigniter - 使用分页,仅显示数据库中的用户数据

javascript - 将选定的目的地从下拉列表删除到另一个下拉列表

php - Doctrine 2 ODM MongoDB 从内存中将图像存储在 GridFS 中

php - 如何在 PHP 中创建 websockets 服务器

php - 如何编辑默认的 artisan 命令 laravel

php - 如何合并两个数组?

php - 原则 2 不坚持从拥有一方到多方的关系