Mwongozo wa kimsingi wa utekelezaji wa Controller- Repository- Service model hukusaidia Laravel kupanga msimbo wako wa chanzo kwa njia ambayo ni rahisi kudhibiti na kudumisha. Hapa kuna mfano halisi wa jinsi unaweza kutekeleza muundo huu:
Model
Hapa ndipo unapofafanua sifa na mbinu za kuingiliana na hifadhidata. Laravel hutoa utaratibu wa Fasaha wa ORM kufanya kazi na mifano. Kwa mfano, wacha tuunde model kwa Posts
meza:
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content'];
}
Repository
Hufanya repository kazi kama mpatanishi kati Controller ya Model. Ina njia za kufanya shughuli za hifadhidata kupitia model. Hii husaidia kutenganisha mantiki ya hifadhidata kutoka kwa controller na kurahisisha kubadilisha au kujaribu mantiki ya hifadhidata.
// 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
Ina service mantiki ya biashara na inawasiliana na Repository. Njia zitapiga Controller simu kutoka kwa Service kushughulikia maombi na kurudisha data inayolingana. Hii husaidia kutenganisha mantiki ya biashara controller na hurahisisha upimaji na matengenezo.
// 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
Hapa controller ndipo unaposhughulikia maombi ya mtumiaji, mbinu za kupiga simu kutoka kwa Service kurejesha au kutuma data, na kurudisha matokeo kwa mtumiaji.
// 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
}
Kwa kutumia muundo huu, unaweza kudhibiti kwa ufanisi sehemu tofauti za Laravel programu yako. Zaidi ya hayo, kutenganisha mantiki ya biashara, mantiki ya kuhifadhi, na mawasiliano kati ya madarasa hufanya codebase yako inyumbulike, iweze kudumishwa, na iweze kujaribiwa.