Laravel 5 package development - Auth::attempt() le

2019-09-08 23:36发布

问题:

I'm developing a package that wraps some of the Laravel User logic, because i want to keep the native implementation while adding some feature to it.

This is my package's composer.json

{
    "name": "foo/bar",
    "description": "A Laravel 5 package",
    "authors": [
        {
            "name": "",
            "email": ""
        }
    ],
    "require": {
        "php": ">=5.4.0",
        "illuminate/auth": "5.1.*"
    },
    "require-dev": {
        "orchestra/testbench": "~3.0"
    },
    "autoload": {
        "psr-4": {
            "Foo\\": "src/Foo/"
        }
    },
    "minimum-stability": "stable"
}

This is a sample code:

class Foo {
    function login($username, $password) { 
        \Auth::attempt($username, $password);
    }
}

This is a sample test case

class UserServiceTest extends \Orchestra\Testbench\TestCase {
    function testLogin() {
        $foo = new Foo();
        $foo->login('foo', 'bar');
    }
}

Now, when running the test i get this PHP Fatal error: Class '\App\User' not found in path/to/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php on line 126

I can understand why (App\User lives in the laravel/laravel package), however i cannot understand how to properly declare my package dependencies.

What should i do in order to reuse the whole Auth and User laravel native implementation?

回答1:

You don't need to use laravel/laravel package in order to reuse Laravel's authentication.

It's enough to just import illuminate/auth package. This will give you 2 out of 3 things that you need to authenticate users:

  • Guard class (usually accessed via Auth facade) that provides authentication method (attempt, check, etc.)
  • User provider that fetches users based on their credentials - this package provides both Eloquent and Database user provider

The last thing you need is a User class, or any Model that implements AuthenticatableContract.

Guard takes user provider as one of its constructor's arguments, and user provider takes the class of a model to use as one of its constructor's arguments.

Those 3 elements are enough to use Laravel's authentication.