Method Resolution
Urutan Resolusi Method
API menggunakan urutan resolusi method yang terstruktur untuk menentukan handler yang tepat untuk setiap request. Berikut adalah urutan resolusinya:
1. Periksa method kustom di URL (slug2)
2. Gunakan method RESTful berdasarkan HTTP verb:
- GET → index()
- POST → created()
- PUT/PATCH → updated()
- DELETE → deleted()
3. Kembali ke index() jika tidak ada method yang ditemukan
Diagram Alur
Request → Check Custom Method → Found? → Execute Custom Method
↓ (not found)
Check HTTP Method → Map to RESTful Method
↓ (not mapped)
Execute Default (index)
Implementasi
Contoh Controller:
class ApiController {
protected function resolveMethod($request) {
// 1. Cek custom method
$customMethod = $request->getSegment(2);
if ($customMethod && method_exists($this, $customMethod)) {
return $this->$customMethod();
}
// 2. Map HTTP method ke RESTful method
$httpMethod = $request->getMethod();
switch ($httpMethod) {
case 'GET':
return $this->index();
case 'POST':
return $this->created();
case 'PUT':
case 'PATCH':
return $this->updated();
case 'DELETE':
return $this->deleted();
}
// 3. Default ke index
return $this->index();
}
}
Contoh Resolusi
1. Custom Method
GET /api/Info/status
↓
Resolves to: InfoController->status()
2. RESTful Method
POST /api/Info
↓
Resolves to: InfoController->created()
3. Default Method
GET /api/Info
↓
Resolves to: InfoController->index()
Best Practices
- Selalu implementasikan method RESTful dasar (index, created, updated, deleted)
- Gunakan nama yang deskriptif untuk custom method
- Hindari konflik nama antara custom method dan RESTful method
- Dokumentasikan semua custom method
- Implementasikan penanganan error untuk method yang tidak ditemukan
Tips Penggunaan
- Gunakan custom method untuk operasi yang tidak sesuai dengan CRUD
- Manfaatkan parameter URL untuk custom method
- Implementasikan middleware sesuai kebutuhan
- Validasi input sebelum eksekusi method
- Gunakan response format yang konsisten