如何使用Repository模式

某天,你无端想起一个人,她曾让你对明天有所期许,但是却完全没有出现在你的明天里。
这里我们介绍一种laravel开发的模式,用于解决控制器过于肥大的问题.

路由 routes.php

1
2
<?php
Route::get('/user', 'UserController@getUser');

控制器 app\Http\Controllers\UserController.php

将新建的库依赖注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

namespace App\Http\Controllers;

use App\Repository\UserRepository;

class UserController extends Controller
{
protected $userRepository;

public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}

public function getUser()
{
return $this->userRepository->getUser();
}
}

模型 app\User.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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',
];
}

新建库 app\Repository\UserRepository.php

将模型依赖注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php namespace App\Repository;

use App\User;

class UserRepository
{
protected $user;

public function __construct(User $user)
{
$this->user = $user;
}

public function getUser()
{
return $this->user->all();
}

}