gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:10:56 24 4
gpt4 key购买 nike

有没有办法扩展 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com