In my recent laravel 5 project, I'm used to prepare my logics as Repository method.
So here's my current directory structure. For example we have 'Car'.
所以首先我只创建目录,将其命名为app
目录下的libs
,并将其加载到composer.json
"autoload": {
"classmap": [
"database",
"app/libs" //this is the new changes (remove this comment)
]
}
然后我创建了一个子文件夹,称之为Car
.在Car文件夹下创建两个文件"CarEloquent".php’用于Eloquent 的实现,CarInterface.php
作为接口.
CarInterface
namespace App\libs\Car;
interface CarInterface {
public function getAll();
public function create(array $data);
public function delete($id);
public function getByID($id);
public function update($id,array $data);
}
CarEloquent
namespace App\lib\Car;
use App\lib\Car\CarInterface;
use App\Car; //car model
class CarEloquent implements CarInterface {
protected $car;
function __construct(Car $a) {
$this->car = $a;
}
public function getAll(){
return $this->car->all();
}
}
然后创建Car Service Provider绑定IOC控制器.
对于创建汽车服务Provider ,您还可以通过laravel使用php artisan命令.
php artisan make:provider CarServiceProvider
个
ServiceProvider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class CarServiceProvider extends ServiceProvider {
public function register() {
$this->app->bind('App\lib\Car\CarInterface', 'App\lib\Car\CarEloquent');
}
}
最后一步是将这些服务Provider 添加到config/app.php
个Provider array.
'providers' => [
'App\Providers\CatServiceProvider',
]
最后,我们准备在控制器中使用我们的存储库方法.
Example Controller
namespace App\Http\Controllers;
use App\lib\Car\CarInterface as Car;
class CarController extends Controller {
protected $carObject;
public function __construct(Car $c) {
$this->carObject = $c;
}
public function getIndex(){
$cars = $this->carObject->getAll();
return view('cars.index')->with('cars',$cars);
}
}
主要目的是实现在这里调用存储库方法来控制,但是您需要根据需要使用它们.
更新
CarEloqent基本上可以帮助我们改进数据库实现,例如,在将来,如果您想为其他数据库(如redis
)实现相同的功能,只需添加另一个类CarRedis
,并从服务器提供程序更改实现文件路径.
更新 1: Good Resource
http://programmingarehard.com/2014/03/12/what-to-return-from-repositories.html
[book] From Apprentice to Artisan by Taylor Otwell
Very good explanation about repository method and software design principle commonly called separation of concerns. You should read this book.
如果您仍然对实现这些行为感到困惑,请让我知道,但如果我发现需要更改或更新或符合要求,我将密切关注这个问题以更新此答案.