在 Laravel 8 中,你可以使用 Repository 模式来处理数据访问逻辑。下面是一个基本的 Laravel 8 Repository 的示例:
- 创建一个 Repository 接口:
<?php
namespace App\Repositories;
interface UserRepositoryInterface
{
public function getAll();
public function getById($id);
public function create(array $data);
public function update($id, array $data);
public function delete($id);
}
- 创建一个 Eloquent Repository 实现该接口:
<?php
namespace App\Repositories;
use App\Models\User;
class UserRepository implements UserRepositoryInterface
{
protected $model;
public function __construct(User $model)
{
$this->model = $model;
}
public function getAll()
{
return $this->model->all();
}
public function getById($id)
{
return $this->model->find($id);
}
public function create(array $data)
{
return $this->model->create($data);
}
public function update($id, array $data)
{
$record = $this->getById($id);
if ($record) {
$record->update($data);
return $record;
}
return null;
}
public function delete($id)
{
$record = $this->getById($id);
if ($record) {
$record->delete();
return true;
}
return false;
}
}
- 在服务容器中注册该 Repository:
在 AppServiceProvider
或其他服务提供者中的 register
方法中添加以下代码:
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
现在,你可以在其他类中通过依赖注入来使用 UserRepository:
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepositoryInterface;
class UserController extends Controller
{
protected $userRepository;
public function __construct(UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = $this->userRepository->getAll();
return view('users.index', compact('users'));
}
// 其他操作方法...
}
这样,你就可以在 UserController
中使用 UserRepository 中定义的方法,通过 Repository 来处理数据逻辑,实现了数据访问层与业务逻辑层的解耦。
请根据你的实际需求调整代码。
希望对你有所帮助!如有任何问题,请随时提问。