petersuhm/laravel-bdd — pull request #2 by petersuhm (2014-07-04 20:44:39+00:00)
Title: Extend Laravel Auth with simple POPOs

By default, Laravel uses Eloquent for authentication. In some instances, you might wish to swap out Eloquent with something else. In this example, I have implemented authentication using a simple `ArrayUserRepository` that "stores" plain old PHP objects (PHP). This is implemented through a BDD approach, using Behat and phpspec. Storing users in an array, is not very suitable in the real world, but with this approach, it is super easy to swap out the repository and use something else. Maybe something like Doctrine.

First, here is the feature that I have implemented:

```gherkin
Feature: Authenticating a user
In order to access restricted content
As a user
I need to be able to authenticate myself

Scenario: Authenticating a user with valid credentials
Given I am registered with the credentials:
| email | password |
| foo@example.com | foob@r |
When I attempt to authenticate myself with the credentials:
| email | password |
| foo@example.com | foob@r |
Then I should see that I am successfully authenticated

Scenario: Authenticating a user with invalid credentials
Given I am registered with the credentials:
| email | password |
| foo@example.com | foob@r |
When I attempt to authenticate myself with the credentials:
| email | password |
| foo@example.com | foobar |
Then I should see that I am not authenticated
```

Here is the service provider that registers the new extension:

```php
app['auth']->extend('suhm_auth', function($app)
{
return $app['Suhm\Storage\UserRepository'];
});
}

public function register()
{
// ...
}
}
```

The repository is implementing Laravel's `UserProviderInterface` that is used by the Auth package:

```php
hasher = $hasher;
}

public function newInstance($input = null)
{
return new User($input);
}

public function persist(User $user)
{
$this->users[] = $user;
}

[...]

/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Auth\UserInterface $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserInterface $user, array $credentials)
{
if (($user->email == $credentials['email']) and $this->hasher->check($credentials['password'], $user->getAuthPassword())) {
return true;
}

return false;
}
}
```

The repository returns users of the type `Suhm\Entity\User` that implements Laravel's `UserInterface`.

The simple `ArrayUserRepository` is bound to the IoC container using a singleton, since the array has to stay in memory during execution:

```php
app->singleton(
'Suhm\Storage\UserRepository',
'Suhm\Storage\ArrayUserRepository'
);
}
}
```

Check the diff in order to see all files!