命名規則?
是的,命名規則(convention)。從thefreedictionary:
可以查到Convention有幾個意思:
-
General agreement on or acceptance of certain practices or
attitudes: By convention, north is at the top of most maps.
-
A practice or procedure widely observed in a group, especially
to facilitate social interaction; a custom: the convention of
shaking hands.
-
A widely used and accepted device or technique, as in drama,
literature, or painting: the theatrical convention of the
aside.
Cake中的命名規則是讓魔法發生的關鍵,我們把它叫automagic。
不用說以命名規則進行一些設定有多好用,Cake甚至讓你的生產力提昇到驚人的等級,卻又不彈性。
Cake裡的命名規則既簡單又直觀。它是由web開發者多年來的實用經驗設計出來的。
檔名
檔名是由底線將文字分開。
一般規則中,名為MyNiftyClass的類別,存放的檔名就得叫my_nifty_class.php。
如果有看到一些Cake的程式片斷,自然就會知道:
-
如果有個Controller名叫KissesAndHugsController,
那它的檔名叫一定叫kisses_and_hugs_controller.php
(注意檔名內的_controller)
-
如果它的Model名稱叫OptionValue,
那它的檔名一定是option_value.php。
-
若是個名叫MyHandyComponent的Component,
那麼檔名就是my_handy.php(和controller不同,不需要加_component)。
-
若是個名為BestHelperEver的Helper,
檔名一定是best_helper_ever.php。
Model
-
Model的類別名稱是單數.
-
Model的類別名稱,若只有一個單字則第一個字大寫,若由多個單字組成則每個單字第一個字母大寫。
例如: Person, Monkey, GlassDoor, LineItem, ReallyNiftyThing
-
多對多Join資料表需命名為:
第一個資料表複數_第二個資料表複數
例如: tags_users
-
Model的檔名用小寫加底線。
例如: person.php, monkey.php, glass_door.php,
line_item.php, really_nifty_thing.php
-
Model對應的資料庫資料表同樣使用小寫加底線,但是用複數。
Database tables related to models also use a lower-case
underscored syntax - but they are plural.
例如: people, monkeys, glass_doors, line_items,
really_nifty_things
譯註:person複數型原來是people!看來還是得懂些英文,難怪我用persons不行!
CakePHP的命名規則主要是要讓程式撰寫更流暢,提昇程式碼的可讀性。
如果你覺得它實在礙手礙腳,那就用自己的方法吧,Cake同樣也可以接受。
但得多做二件事:
-
定Model名稱: 在model定義中設定$name變數。
-
定Model對應的資料表:在model定義中設定$useTable變數
View
-
View由顯示他們的action名稱命名
-
將檔名命名為action名稱的小寫。
例如: PeopleController::worldPeace() 需要一個view,檔名為
/app/views/people/world_peace.thtml;
MonkeysController::banana() 需要一個view,檔名
/app/views/monkeys/banana.thtml.
也可以強制action使用某一個view,只要在action結束前呼叫$this->render('view檔名去除副檔名後的字串');。
Helper
-
Helper類別名稱是以第一個字母大寫的單字組成,最後面再加上"Helper"字串。檔名則使用小寫加底線去除"helper"。
例如: MyClarinetHelper放在/app/views/helpers/my_clarinet.php內。
在controller中引用的方式為:var $helpers = array('Html','MyHelper');。
接著就可以在view裡這麼呼叫:$myHelper->method().
Component
-
Component類別名稱是以第一個字母大寫的單字組成,最後面再加上"Component"字串。檔名則使用小寫加底線去除"component"。
範例: MyComponentComponent放在
/app/controllers/components/my_component.php中
-
在controller內引用方式為:var $components array('MyComponent');。
接著在controller內呼叫$this->MyComponent->method()。
Vendor
Vendor沒有任何命名規則,原因很簡單:他們是第三方的程式碼,Cake對他們沒有控制權。