0

使用 Laravel Spark,如果我想为configureTeamForNewUser.Spark::interact

#File: spark/src/Interactions/Auth/Register.php
Spark::interact(self::class.'@configureTeamForNewUser', [$request, $user]);

即框架调用configureTeamForNewUserusing Spark::interact,这意味着我可以Spark::swap

但是,如果我看一下configureTemForNewUser方法本身

#File: spark/src/Interactions/Auth/Register.php
public function configureTeamForNewUser(RegisterRequest $request, $user)
{
    if ($invitation = $request->invitation()) {
        Spark::interact(AddTeamMember::class, [$invitation->team, $user]);

        self::$team = $invitation->team;

        $invitation->delete();
    } elseif (Spark::onlyTeamPlans()) {
        self::$team = Spark::interact(CreateTeam::class, [
            $user, ['name' => $request->team, 'slug' => $request->team_slug]
        ]);
    }

    $user->currentTeam();
}

此方法为私有$team类属性分配一个值。我的理解是,如果我使用Spark::swap我的回调而不是原始方法被调用。初步测试证实了这一点。但是,由于我的回调不能设置$team,这意味着我的回调会以一种会破坏其他火花功能的方式改变系统的行为。

以上是对系统的正确理解吗?或者我错过了什么,并且可以swap在另一个函数调用中(以某种方式调用原来的configureTeamForNewUser)?

4

1 回答 1

-1

当然,您可以交换此configureTeamForNewUser方法。Spark 在注册时为用户创建一个团队。Booted()您必须在App/Providers/SparkServiceProvider.php 类的方法中添加 swap 方法。在下面的顶部使用中,

use Laravel\Spark\Contracts\Interactions\Auth\Register;
use Laravel\Spark\Contracts\Http\Requests\Auth\RegisterRequest;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\CreateTeam;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\AddTeamMember;

就我而言,我想将新字段调用“custom_one”添加到团队表中。在booted()方法内部,如下交换方法。

Spark::swap('Register@configureTeamForNewUser', function(RegisterRequest $request, $user){
if ($invitation = $request->invitation()) {
 Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
   self::$team = $invitation->team;
   $invitation->delete();
 } elseif (Spark::onlyTeamPlans()) {
   self::$team = Spark::interact(CreateTeam::class, [ $user, 
         [
            'name' => $request->team,
            'slug' => $request->team_slug,
            'custom_one' => $request->custom_one, 
         ] ]);
}
  $user->currentTeam();
});  

为了添加一个新的 custom_one 字段,我也必须交换TeamRepository@create方法。交换configureTeamForNewUser方法后,交换 booted() 上的 TeamRepository@create 方法,

Spark::swap('TeamRepository@create', function ($user,  $data) {
                $attributes = [
                    'owner_id' => $user->id,
                    'name' => $data['name'],
                    'custom_one' => $data['custom_one'],
                    'trial_ends_at' => Carbon::now()->addDays(Spark::teamTrialDays()),
                ];

            if (Spark::teamsIdentifiedByPath()) {
                $attributes['slug'] = $data['slug'];
            }
            return Spark::team()->forceCreate($attributes);
        });

然后继续您的注册。

请参阅Laravel Spark 文档

于 2017-06-23T09:08:55.397 回答