我可以在 Laravel 5.2 中创建一个继承自 User 的新类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34653415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:59:52  来源:igfitidea点击:

Can I create a new class that inherits from User in Laravel 5.2?

phpooplaravellaravel-5laravel-5.2

提问by idelara

I am pretty new to laravel (using 5.2 which is the latest version to date), therefore I have the following dilemma: I know that Laravel comes with a Userclass right out of the box, but I want to develop a system where I can have another two types of users called Researcherand Admin.

我对 Laravel 很陌生(使用 5.2,这是迄今为止的最新版本),因此我有以下两难:我知道 Laravel 带有一个开箱即用的User类,但我想开发一个系统,我可以拥有另外两种类型的用户称为ResearcherAdmin

My main need to create completely different classes of users (Researcher and Admin), possibly inheriting from Userbecause the business logic is almost 100% different amongst them and I would not want to create a column in the database to classify the type of user. Furthermore, there aren't many fields that overlap between the stock User, Adminand Researcherclasses.

我的主要需求是创建完全不同的用户类别(研究人员和管理员),可能是继承自User因为业务逻辑在他们之间几乎 100% 不同,我不想在数据库中创建一列来对用户类型进行分类。此外,不会有太多的领域,股市之间的重叠UserAdmin以及Researcher类。

My main question would be: Will everything still work the same (Auth Controller, middleware enabled, etc...) if I inherit from Userfor my other 2 classes? I know the principles of OOP and by intuition I assume I should be fine if I do the following:

我的主要问题是:如果我从User其他 2 个类继承,一切是否仍然有效(身份验证控制器、启用中间件等...)?我知道 OOP 的原则,并且根据直觉,我认为如果我执行以下操作应该没问题:

//'Stock' User class:
//
class User extends Authenticatable{
    //Any overlapping logic between Researcher and Admin.
}


class Researcher extends User{
    //My class definition here.
}

class Admin extends User{
    //My class definition here.
}

And then use both classes as I would normally use an instance of the class User. By that, I mean use all the methods and right out of the box Userfunctionality.

然后像我通常使用类的实例一样使用这两个类User。我的意思是使用所有方法和开箱即用的User功能。

QUESTION EXTENSION: While writing my question, I realize that the class Userlooks like so by default:

问题扩展:在写我的问题时,我意识到User默认情况下该类看起来像这样:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Could not I just do the following instead of inheriting from Userto create my other 2 classes (Researcher& Admin):

我不能只执行以下操作而不是继承User来创建我的其他 2 个类 ( Researcher& Admin):

//Researcher Class:
namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Researcher extends Authenticatable
{
    //Class definition...
}

...

//Admin Class:
namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    //Class definition
}

In this approach, I am trying to 'mimic' the Userclass. The thing is that I don't know if there is any logic in the Kernel that is hardcoded and is being referenced to the Userclass implicitly.

在这种方法中,我试图“模仿”User课程。问题是我不知道内核中是否有任何逻辑是硬编码的并且被User隐式引用到类。

Any thought and help will be much appreciated. Sorry if this is silly to you. I am just getting started with the laravel framework.

任何想法和帮助将不胜感激。对不起,如果这对你来说很愚蠢。我刚刚开始使用 laravel 框架。

Cheers!

干杯!

回答by Moppo

Yes, you can extend the class Illuminate\Foundation\Auth\User:

是的,您可以扩展该类Illuminate\Foundation\Auth\User

use Illuminate\Foundation\Auth\User as Authenticatable;

class Researcher extends Authenticatable {
    //My class definition here.
}

If you take a look at Userclass:

如果你看一下User类:

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
}

you see that it extends the Modelclass and implements all the other useful interfaces for authentication handling

您会看到它扩展了Model该类并实现了所有其他用于身份验证处理的有用接口

you can safely extend the Userclass, because Laravel is good enough to work with the Illuminate\Contracts\Auth\Authenticatableinterface to handle the authenticationand not directly with the Userclass

您可以安全地扩展User该类,因为 Laravel 足以与Illuminate\Contracts\Auth\Authenticatable接口一起工作来处理身份验证,而不是直接与User该类一起工作

In fact if you check in:

事实上,如果您办理登机手续:

Illuminate/Auth/SessionGuard.php

That is the main class for auth handling, you'll see that all the auth actions are made against the Illuminate\Contracts\Auth\Authenticatableinterface, i.e:

这是身份验证处理的主要类,您将看到所有身份验证操作都是针对Illuminate\Contracts\Auth\Authenticatable接口进行的,即:

/**
 * Log a user into the application.
 *
 * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
 * @param  bool  $remember
 * @return void
 */
public function login(AuthenticatableContract $user, $remember = false)
{
    //other code
} 

I Think that your real problem would be: how to instantiate the classes Researcherand Admininstead of the Userclass during the authentication process?

我认为您真正的问题是:如何在身份验证过程中实例化类ResearcherAdmin不是User类?

If you use Eloquent as authentication driver, by default Laravel is going to use the Illuminate\Auth\EloquentUserProviderto create an instance of the Model. So, if you want to create an instance one of your classes instead of User, you should override this provider (or create one of your own) and here you could choose which class to instantiate

如果您使用 Eloquent 作为身份验证驱动程序,默认情况下 Laravel 将使用Illuminate\Auth\EloquentUserProvider来创建模型的实例。因此,如果您想创建一个类的实例而不是User,您应该覆盖此提供程序(或创建您自己的提供程序),并且您可以在此处选择要实例化的类

回答by Dan Palmieri

I think the best way to work with this concept is with roles and keeping the User Class intact. See https://github.com/spatie/laravel-permissionfor details.

我认为处理这个概念的最好方法是使用角色并保持用户类完整。有关详细信息,请参阅https://github.com/spatie/laravel-permission