首页 > 解决方案 > 可以在对象中动态添加特征吗?

问题描述

我想在对象中动态添加/设置一个特征。我该怎么做?

例如我有$object

$object->setTrait($someTrait);

感谢帮助。
编辑

<?php

namespace GamApi\Models\Traits;

use GamApi\Scopes\OrganizationScope;

/**
 *
 * Trait BelongsToOrganizationTrait
 * @package GamApi\Models\Traits
 */
trait BootOrganization
{
    /**
     * For saving resource auto-complete organization_id attribute
     * Add global OrganizationScope
     *
     */
    public static function boot()
    {
        parent::boot();

        // global organization_id scope
        static::addGlobalScope(new OrganizationScope());

        // set organization_id for saving
        static::creating(function ($model){
            if (defined('ORGANIZATION_ID')) {
                $model->organization_id = ORGANIZATION_ID;
            }
        });
    }
}

我想测试这个类,我认为我可以$object动态地制作insert Trait to the object然后测试Trait boot方法。

标签: phplaravelreflection

解决方案


推荐阅读