如何减少laravel中策略文件的代码?



我有两个文件userPolicy.phpuserObserver.php,我在这两个文件中写了一些逻辑,这意味着如果一个用户有任何活跃的订阅,用户不会被删除,它的工作很好。

userPolicy.php

public function delete(User $user, $item)
{
$canceled_subscription=new userObserver();
return (!$canceled_subscription->deleting($item)) && ($user->hasAdminRole());    
}

userObserver.php

public function deleting(Plan $item){
//based on $has_subscriptions it should allow to delete or call the userPolicy.php delete function
$has_subscriptions=$item->subscriptions()->where('status','!=','canceled')->exists();
return $has_subscriptions;
}

现在我想要的是我想重构代码从userPolicy.php这意味着有任何方法来减少代码从userPolicy.php文件(主要是$canceled_subscriptions),是否有任何机会减少代码从userPolicy.php请帮助我重构代码

我更喜欢通过分离条件来保持代码的整洁,这样更容易快速理解。你可以在你的User Observer中使用一个静态函数,如下面的例子所示。

// UserPolicy
public function delete(User $user, $item) 
{
if (! $user->hasAdminRole()) return false;
return UserObserver::deleting();
}
// UserObserver
public static function deleting(Plan $item)
{
return $item->subscriptions()->where('status','!=','canceled')->exists();
}

最新更新