【问题标题】:Builder for entities with cakephp3cakephp3 实体的构建器
【发布时间】:2016-12-12 16:27:10
【问题描述】:

我在 CakePhp 3 中的实体方面需要一些帮助。 这个想法是在初始化阶段为新实体设置一些参数。也许有一个构建器(函数 _setPrivateKey( ) )。

我真的不明白我该怎么做。

当我写作时:

$this->Univer->newEntity();

我想自动设置一个属性:例如我想直接生成$cleAuthentification而不在我的控制器中写入$univer->cleAuthentification = ramdomGenerate();。但是在实体类中有一个方法。 (我喜欢其他语言的构建器)但是我该怎么做呢?

这是我的实体类:

use Cake\ORM\Entity;

/**
 * Univer Entity
 *
 * @property int $id
 * @property int $actif
 * @property string $cleAuthentification
 * @property string $clePrivee
 * @property string $clePublique
 * @property \Cake\I18n\Time $dateCreation
 * @property \Cake\I18n\Time $dateRelance
 * @property \Cake\I18n\Time $dateValidation
 * @property \Cake\I18n\Time $dateDernierAppel
 * @property string $domaine
 * @property string $nom
 * @property bool $refreshActif
 * @property string $traficMensuelCaptcha
 * @property string $traficMensuelSite
 * @property int $version
 * @property int $categorie_id
 * @property int $editeur_id
 * @property string $plugin
 * @property int $visiteurUniqueMensuel
 * @property int $saisieMensuelValide
 * @property int $clicMensuel
 * @property int $saisieUniqueMensuel
 * @property bool $getContent
 * @property bool $displayTab
 * @property bool $escape
 * @property bool $restrictionLDA
 * @property int $genre
 * @property string $age
 * @property float $cpeMin
 * @property string $dataComportementale
 *
 * @property \App\Model\Entity\TechnologyIntegration $technologyIntegration
 * @property \App\Model\Entity\Categorie $categorie
 * @property \App\Model\Entity\Editeur $editeur
 * @property \App\Model\Entity\Theme[] $theme
 */
class Univer extends Entity
{
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];
}
`

感谢您的帮助!

【问题讨论】:

  • 您想在将实体保存到数据库之前为其添加额外的属性?
  • 请发布一些代码并更清楚
  • 我编辑了帖子

标签: cakephp-3.0 entities


【解决方案1】:

一个非常简单的方法是在实体中创建一个方法,如下所示:

public function initializeValues() {
    $this->foo = "bar";
    $this->cleAuthentification = this->randomGenerate();
}

然后执行以下操作:

$entity = $this->Univer->newEntity();
$entity->initializeValues();

或者,如果在您想要保存实体时这样做就足够了,您可以将代码放在 Table 类的 beforeSave() 方法中 - 请参阅此处的文档:http://book.cakephp.org/3.0/en/orm/table-objects.html#beforesave :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2011-08-19
    • 2014-05-20
    相关资源
    最近更新 更多