CakePHP命名约定

来源:互联网 发布:python多线程加锁 编辑:程序博客网 时间:2024/04/30 06:27

CakePHP提倡约定优于配置(Convention over Configuration),在基于CakePHP的应用中使用恰当的命名约定,将为你节省大量的时间。

Controller约定

类名(Class Name)采用复数、驼峰式命名,并且以Controller结束,如:UsersController、ArticleCategoriesController。
公共方法(Public Method)通常暴露为可被浏览器直接访问的“actions”,如:/users/view 被映射到UsersController中的view()方法。
受保护的和私有方法不能够通过上面的路由方式访问。

为Controller设计URL

以单个单词命名的Controller映射为简单全小写的URL路径,而以多个单词命名的Controller至少有两种映射URL的方式:
1、使用DasedRoute类,URL路径全小写且使用连字符(“-”)进行连接,如使用 /article-categories/view-all 可以访问ArticleCategoriesController::viewAll()方法。
2、当使用 this->Html->link() 方法创建链接时,则可以使用如下方式:

$this->Html->link('link-title', [    'prefix' => 'MyPrefix' // CamelCased    'plugin' => 'MyPlugin', // CamelCased    'controller' => 'ControllerName', // CamelCas ed    'action' => 'actionName' // camelBacked]

文件名和类名

通常情况下,文件名和类名应该保持一致,并以该类的“类型名称”结束,如:

  • The Controller class LatestArticlesController would be found in a file named LatestArticlesController.php.
  • The Component class MyHandyComponent would be found in a file named MyHandyComponent.php.
  • The Table class OptionValuesTable would be found in a file named OptionValuesTable.php.
  • The Entity class OptionValue would be found in a file named OptionValue.php.
  • The Behavior class EspeciallyFunkableBehavior would be found in a file named EspeciallyFunkableBehavior.php.
  • The View class SuperSimpleView would be found in a file named SuperSimpleView.php.
  • The Helper class BestEverHelper would be found in a file named BestEverHelper.php.

每个文件都应该放在以合适类型命名的文件夹下。

Model和Database约定

Table类以复数、驼峰式命名,并以Table结束,如UsersTable、ArticleCategoriesTable、UserFavoritePagesTable。

数据表与Table形成映射关系,并以复数、全小写和下划线的方式命名,如与上面提到的Model对应的是users、article_categories、user_favorite_pages。

约定使用标准的英文单词来为数据表和字段命名,字段名通用采用全小写和下划线的形式,如first_name。

外键使用 xxx_id 的形式命名,如user_id、article_category_id。

连接表使用要连接的表名在前、被连接的表名在后的形式命名,如articles_tags,而不是tags_articles。

可以使用UUID作为数据表的主键,在使用如 Table::save() 之类的方法进行保存新记录时,CakePHP会自动生成一个唯一的32位UUID。

View约定

view文件名与Controller中的方法名形成映射,但是以全小写和下划线的形式命名,如ArticlesController中的viewAll()方法对应的视图文件为:src/Template/Articles/view_all.ctp。

其基本匹配模式为:src/Template/Controller/underscored_function_name.ctp。

综合示例

  • 数据表:articles
  • Table类:src/Model/Table/ArticlesTable.php
  • Entity类:src/Model/Entity/Article.php
  • Controller类:src/Controller/ArticlesController.php
  • View: src/Template/Articles/index.ctp

使用上述命名约定,在访问诸如http://xxx.com/articles等路径时,CakePHP会自动调用ArticlesController中的index()方法,Articles Model会自动生效,并与数据表articles产生连接。

1 0