I've spent quite a bit of time studying the repository and entity patterns and this is what I came up with. I would appreciate it if you could post suggestions and critique.
User entity
:
<?php
namespace Huntitapp\Entities\Entities\User;
use
Huntitapp\Entities\Abstracts\AbstractEntity,
Huntitapp\Repositories\Interfaces\UserRepositoryInterface as UserRepository,
Huntitapp\Services\Validation\Laravel\UserLoginValidator,
Str,
Exception,
ExceptionHandler,
stdClass,
MessageBag;
class UserEntity extends AbstractEntity
{
protected $loginValidator;
public function __construct(
UserRepository $repository
UserLoginValidator $loginValidator
)
{
$this->repository = $repository;
$this->loginValidator = $loginValidator;
}
public function login(array $input)
{
$result = $this->validate($this->loginValidator, $input);
if(!$result instanceof MessageBag)
{
try
{
$user = $this->repository->authenticate(array(
'email' => $input['email'],
'password' => $input['password']
), false);
$user->access_token = hash('sha256', Str::random(10), false);;
$this->save($user);
$user->type = $user->getGroups()[0]->id;
$result = new stdClass;
$result->errors = false;
$result->status_code = 23;
$result->user = $user->toArray();
return $result;
}
catch (Exception $e)
{
return ExceptionHandler::returnException($e);
}
}
else
return $this->loginValidator->returnErrors();
}
}
User Repository
:
<?php
namespace Huntitapp\Repositories\Eloquent\User;
use
Huntitapp\Repositories\Abstracts\AbstractRepository,
Huntitapp\Repositories\Interfaces\UserRepositoryInterface,
Cartalyst\Sentry\Sentry as Sentry,
Cartalyst\Sentry\Users\Eloquent\User as SentryUser;
class EloquentUserRepository extends AbstractRepository implements UserRepositoryInterface
{
public function __construct(Sentry $model)
{
$this->model = $model;
}
public function find($id)
{
return $this->model->findUserById($id);
}
public function save(SentryUser $model)
{
return $model->save();
}
public function getAccessToken()
{
return $this->model->getUser()->access_token;
}
}
?>
User controller
:
<?php
namespace Controllers\API;
use
BaseController,
Input,
ResponseSender,
Huntitapp\Entities\Entities\User\UserEntity;
class UserController extends BaseController
{
protected $user;
public function __construct(UserEntity $user)
{
$this->user = $user;
}
public function postLogin()
{
return ResponseSender::send($this->user->login(Input::all()));
}
}
?>