2.4.3 Konvensi Controller
Nama class controller berbentuk plural, CamelCase, dan diakhiri dengan Controller. Contoh konvensi penamaan controller adalah PeopleController dan LatestArticlesController.
Fungsi pertama yang mungkin ditulis adalah fungsi index(). Saat ada request dengan menyertakan controller tanpa parameter action, CakePHP secara default akan mengeksekusi fungsi index() di controller tersebut. Misal, request ke http://www.example.com/apples/ akan memanggil fungsi index() di controller ApplesController, sedangkan request ke http://www.example.com/apples/view/ akan memanggil fungsi view() di controller ApplesController.
Anda juga dapat mengubah akses fungsi di controller dengan menyisipkan underscore di awal nama fungsi tersebut. Jika nama fungsi di controller diawali dengan underscore, maka fungsi tersebut tidak dapat diakses secara langsung dari web melainkan hanya melalui pemanggilan internal. Contohnya:
<?php
class NewsController extends AppController {
function latest() {
$this->_findNewArticles();
}
function _findNewArticles() {
//Logic to find latest news articles
}
}
?>
<?phpclass NewsController extends AppController {function latest() {$this->_findNewArticles();}function _findNewArticles() {//Logic to find latest news articles}}?>
Pertimbangan URL untuk Nama Controller
Sebagaima telah Anda lihat, nama controller dengan satu kata akan merujuk ke path URL dengan huruf kecil. Misal, ApplesController (didefinisikan dalam berkas 'apples_controller.php') dapat diakses melalui http://example.com/apples.
Nama controller yang lebih dari satu kata menggunakan konvensi camelCase dengan bentuk plural untuk URLnya. Misal, RedApplesController (red_apples_controller.php) akan merujuk ke http://example.com/redApples dan OperatingSystemsController (operating_systems_controller.php) akan merujuk ke http://example.com/operatingSystems.
2.4.3.1 Kaitan URL terhadap Penamaan Controller
Sebagaimana Anda lihat, penamaan controller dengan satu kata secara mudah dipetakan ke path URL dalam bentuk lower case. Contohnya, ApplesController (yang mungkin didefinisikan dalam berkas 'apples_controller.php') dapat diakses melalui http://example.com/apples.
Nama controller yang terdiri lebih dari satu kata dipetakan ke URL secara camelCased dengan bentuk plural. Contohnya, RedApplesController (red_apples_controller.php) akan dipetakan ke http://example.com/redApples dan OperatingSystemsController (operating_systems_controller.php) akan dipetakan ke http://example.com/operatingSystems.
