Pandhuan implementasi dhasar kanggo Controller- Repository- Service model ing Laravel mbantu sampeyan ngatur kode sumber kanthi cara sing gampang kanggo ngatur lan njaga. Mangkene conto konkrit babagan carane sampeyan bisa ngetrapake struktur iki:
Model
Iki ngendi sampeyan nemtokake atribut lan cara kanggo sesambungan karo database. Laravel nyedhiyakake mekanisme ORM Eloquent kanggo nggarap model. Contone, ayo nggawe model kanggo Posts
tabel:
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content'];
}
Repository
Tumindak repository minangka perantara antarane Controller lan Model. Isine cara kanggo nindakake operasi database liwat file model. Iki mbantu kanggo misahake logika database saka lan controller nggampangake kanggo ngganti utawa nyoba logika database.
// app/Repositories/PostRepository.php
namespace App\Repositories;
use App\Models\Post;
class PostRepository
{
public function create($data)
{
return Post::create($data);
}
public function getAll()
{
return Post::all();
}
// Other similar methods
}
Service
Isine service logika bisnis lan komunikasi karo Repository. Ing Controller bakal nelpon cara saka Service kanggo nangani panjalukan lan bali data sing cocog. Iki mbantu kanggo misahake logika bisnis saka controller lan nggawe testing lan pangopènan luwih gampang.
// app/Services/PostService.php
namespace App\Services;
use App\Repositories\PostRepository;
class PostService
{
protected $postRepository;
public function __construct(PostRepository $postRepository)
{
$this->postRepository = $postRepository;
}
public function createPost($data)
{
return $this->postRepository->create($data);
}
public function getAllPosts()
{
return $this->postRepository->getAll();
}
// Other similar methods
}
Controller
Ing controller ngendi sampeyan nangani panjalukan pangguna, nelpon cara saka kanggo Service njupuk utawa ngirim data, lan ngasilake asil menyang pangguna.
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\PostService;
class PostController extends Controller
{
protected $postService;
public function __construct(PostService $postService)
{
$this->postService = $postService;
}
public function create(Request $request)
{
$data = $request->only(['title', 'content']);
$post = $this->postService->createPost($data);
// Handle the response
}
public function index()
{
$posts = $this->postService->getAllPosts();
// Handle the response
}
// Other similar methods
}
Kanthi ngetrapake struktur iki, sampeyan bisa ngatur macem-macem bagean Laravel aplikasi sampeyan kanthi efisien. Kajaba iku, misahake logika bisnis, logika panyimpenan, lan komunikasi ing antarane kelas nggawe basis kode sampeyan fleksibel, bisa dijaga, lan bisa diuji.