Laravel Spark,交换/交互和私有变量

时间:2017-06-22 01:03:58

标签: php laravel laravel-spark

使用Laravel Spark,如果我想交换configureTeamForNewUser的新实现,首先看起来可能是因为此处Spark::interact调用

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

即。框架使用configureTeamForNewUser调用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)?

1 个答案:

答案 0 :(得分:-1)

当然,您可以交换此configureTeamForNewUser方法。 Spark在注册时为用户创建了一个团队。您必须在App / Providers / SparkServiceProvider.php类的Booted()方法中添加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 documentation