Вы находитесь на странице: 1из 14

Coding Standards

PHP tags Always use long tags: <?php ?> Never use short tags: <? ?> or the short version of echo commonly used in views: <?= $var ?> as this can cause problems with xml files.

Indentation One tab should be used for one indentation level. A tab should use spaces rather than a tab character so indentation is preserved and consistent across platforms and media. Tab-width: 4 spaces. This can normally be configured in your editor when you hit the tab key. Ensure everyone working on the project uses this convention otherwise merging changes in subversion can be a pain. // base level // level 1 // level 2 // level 1 // base level

Control structures Control structures are for example if, for, foreach, while, switch etc. Below, an example with if: If ((expr_1) || (expr_2)) { // action_1; } elseif (!(expr_3) && (expr_4)) { // action_2; } else { // default_action; } In the control structures there should be one space between the last parenthesis and the opening bracket. Always use curly brackets in control structures, even if they are not needed. They increase the readability of the code, and they give you fewer logical errors. Opening curly brackets should be placed on the same line as the control structure. Closing curly brackets should be placed on new lines, and they should have same indentation level as the control structure. The statement included in curly brackets should begin on a new line, and code contained within it should gain a new level of indentation. (K&R style) // wrong - no brackets, badly placed statement if (expr) statement; // wrong - no brackets if (expr) statement; // good if (expr) { statement; } Where multiple comparisons exist in a condition, each comparison should be parenthesized to clearly define as a separate comparison. e.g. if($a == 'q' || $a == 'r') Should be written as: if(($a == 'q') || ($a == 'r'))

Ternary Operator Only use the ternary operator (<?php $a = $b == $c ? $d : $e ?>) for very simple comparisons. Using full if-else calls makes code more readable and easier to debug. Dont nest ternary operators.

Function calls Functions should be called without space between functions name and starting bracket. There should be one space between every parameter of a function call. $var = foo($bar, $bar2, $bar3); As you can see above there should be one space on both sides of equals sign. To increase the redability of the code you can add spaces before the equals sign, but only in the case of a multiple function call presented below: $varShort = foo($bar1);

$variableLong = foo($bar1);

String definition All strings should be delimited by apostrophes unless quotes are required for interpolation purposes such as if the string contains apostrophes, variables, newline characters etc. $string1 = 'This is a normal string so it delimited by apostrophes'; $string2 = "This string contains an apostrophe ', a $variable and\nspans 2 lines";

Array definition Arrays should be defined thus: $array = array( 'key1' => array( 'key1.1' => 'value1', 'key1.2' => array( 'key1.2.1' => 'value2', ), ), 'key2' => 'value', ); unless the array is small $array = array('red', 'blue', 'green');

Method definition Example of a function definition: function someFunction($arg1, $arg2 = '') { } Parameters with a default value, should be placed last in function definition. Try to make your functions return something, at least true or false so it can be determined whether the function call was successful.

Operators Operators should be surrounded by a single space on each side. Example: $x = $y + $z;

Commenting code /** * Comments that span multiple lines * should use this style. */ // Use this for single line comments Classes, their methods and properties and procedural functions should be immediately preceded by comments that include some or all of the following phpDocumentator tags: @access @author @copyright @deprecated @example @ignore @internal @link @param @return @see @since @tutorial @version inline {@internal}} inline {@inheritdoc}} inline {@link}}

An example class illustrating proper comments: /** * Class to print <Message> <Name> * @author NeilC */ class HelloWorld { /** * First part of message returned by {@link display()} * * @var string * @access public */ var $text = 'Hello '; /** * Returns HTML blink tag containing the value * of $this->text and the name sent to the method * * @param string $name Name to display, defaults to John * @return string * @access public */ function display($name = 'John') { echo '<blink>'.$this->text.$name.'</blink>'; return true; } }

Variable types Variable types for use in DocBlocks: Type mixed integer float boolean string array object resource Description A variable with undefined (or multiple) type. Integer type variable (whole number). Float type (point number). Logical type (true or false). String type (any value in or ). Array type. Object type. Resource type (returned by for example mysql_connect()).

Remember that when you specify the type as mixed, you should indicate whether it is unknown, or what the possible types are.

Including files When including files with classes or libraries, use only and always the require_once function. In making includes in the app folder, use the bootstrap to call general functions and use vendor() instead of require_once(). All included files should then be placed in the vendors folder. Example call in the /core/bootstrap.php vendor('functions');

Naming conventions
Functions Function names should be written in camelBack?, for example: function longFunctionName() { } For functions that are used as controller actions and views pages, use underscores to break words and all lower caps. Example: function long_function_name() { }

Classes Class names should be written in CamelCase, for example: class ExampleClass { }

Variables Variable names should be as descriptive as possible, but also as short as possible. Normal variables should start with a lowercase letter, and should be written in camelBack in case of multiple words. Variables containing objects should start with a capital letter, and in some way associate to the class the variable is an object of. Example: $x = 123; $blogPosts = array(); $Dispatcher = new Dispatcher();

Member visibility In addition to using PHP5's private and protected keywords for methods or variables, a protected method or variable name should start with a single underscore (_). Example: class A { var _iAmAProtectedVariable; function _iAmAProtectedMethod() { } } A private method or variable name should start with double underscore (__). Example: class A { var __iAmAPrivateVariable; function __iAmAPrivateMethod() { } }

Constants Constants should be defined in capital letters: define('CONSTANT', 1); If a constant name consists of multiple words, they should be separated by an underscore character, for example: define('LONG_NAMED_CONSTANT', 2); All global constants should be declared in the /config/bootstrap.php

SQL Guidelines $this->find(all, array( conditions => array( Post.id => 1, Post.is_active => 1 ) );

PHP code in views Try not to echo out markup, open PHP tags and echo content into markup wherever possible, this facilitates markup maintenance and modification by developers that are not familiar with PHP syntax and can therefore just ignore any PHP code, while still being able to edit the HTML. Whenever you close PHP tags within a control stucture, always use the colon, end-control-structure syntax, so that it is clearer which control structure you are closing, e.g. <?php if (....) : ?> <p>html markup here</p> <?php endif; ?> rather than this <?php if (....){ ?> <p>html markup here</p> <?php } ?> If you need to nest control structures, always use a separate line for each, e.g. <?php foreach ($a as $b): ?> <?php if ($b == $c): ?> <p>html markup here</p> <?php endif; ?> <?php endforeach; ?> not the following: <?php foreach ($a as $b): if($b == $c): ?> <p>html markup here</p> <?php endif; endforeach; ?>

CakePHP Conventions
We are big fans of convention over configuration. While it takes a bit of time to learn CakePHPs conventions, you save time in the long run: by following convention, you get free functionality, and you free yourself from the maintenance nightmare of tracking config files. Convention also makes for a very uniform system development, allowing other developers to jump in and help more easily. CakePHPs conventions have been distilled out of years of web development experience and best practices. While we suggest you use these conventions while developing with CakePHP, we should mention that many of these tenets are easily overridden something that is especially handy when working with legacy systems.

Controller Conventions Controller classnames are plural, CamelCased, and end in Controller. PeopleController and LatestArticlesController are both examples of conventional controller names. The first method you write for a controller might be the index() method. When a request specifies a controller but not an action, the default CakePHP behavior is to execute the index() method of that controller. For example, a request for http://www.example.com/apples/ maps to a call on the index() method of the ApplesController, whereas http://www.example.com/apples/view/ maps to a call on the view() method of the ApplesController. You can also change the visibility of controller methods in CakePHP by prefixing controller method names with underscores. If a controller method has been prefixed with an underscore, the method will not be accessible directly from the web but is available for internal use. For example: class NewsController extends AppController { public function latest() { $this->_findNewArticles(); } protected function _findNewArticles() { // Logic to find latest news articles } } While the page http://www.example.com/news/latest/ would be accessible to the user as usual, someone trying to get to the page http://www.example.com/news/_findNewArticles/ would get an error, because the method is preceded with an underscore. You can also use PHPs visibility keywords to indicate whether or not a method can be accessed from a url. Non-public methods cannot be accessed.

URL Considerations for Controller Names As youve just seen, single word controllers map easily to a simple lower case URL path. For example, ApplesController (which would be defined in the file name ApplesController.php) is accessed from http://example.com/apples. Multiple word controllers can be any inflected form which equals the controller name so: /redApples /RedApples /Red_apples /red_apples will all resolve to the index of the RedApples controller. However, the convention is that your urls are lowercase and underscored, therefore /red_apples/go_pick is the correct form to access the RedApplesController::go_pick action. For more information on CakePHP URLs and parameter handling, see Routes Configuration.

File and Classname Conventions In general, filenames match the classnames, which are CamelCased. So if you have a class MyNiftyClass, then in Cake, the file should be named MyNiftyClass.php. Below are examples of how to name the file for each of the different types of classes you would typically use in a CakePHP application: The Controller class KissesAndHugsController would be found in a file named KissesAndHugsController.php The Component class MyHandyComponent would be found in a file named MyHandyComponent.php The Model 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 Each file would be located in the appropriate folder in your app folder.

Model and Database Conventions Model classnames are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names. Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.

You can use the utility library Inflector to check the singular/plural of words. See the Inflector for more information. Field names with two or more words are underscored like, first_name. Foreign keys in hasMany, belongsTo or hasOne relationships are recognized by default as the (singular) name of the related table followed by _id. So if a Baker hasMany Cake, the cakes table will refer to the bakers table via a baker_id foreign key. For a multiple worded table like category_types, the foreign key would be category_type_id. Join tables, used in hasAndBelongsToMany (HABTM) relationships between models should be named after the model tables they will join in alphabetical order (apples_zebras rather than zebras_apples). All tables with which CakePHP models interact (with the exception of join tables), require a singular primary key to uniquely identify each row. If you wish to model a table which does not have a singlefield primary key, CakePHPs convention is that a single-field primary key is added to the table. You have to add a single-field primary key if you want to use that tables model. CakePHP does not support composite primary keys. If you want to directly manipulate your join table data, use direct query calls or add a primary key to act on it as a normal model. E.g.: CREATE TABLE posts_tags ( id INT(10) NOT NULL AUTO_INCREMENT, post_id INT(10) NOT NULL, tag_id INT(10) NOT NULL, PRIMARY KEY(id)); Rather than using an auto-increment key as the primary key, you may also use char(36). Cake will then use a unique 36 character uuid (String::uuid) whenever you save a new record using the Model::save method.

View Conventions View template files are named after the controller functions they display, in an underscored form. The getReady() function of the PeopleController class will look for a view template in /app/View/People/get_ready.ctp. The basic pattern is /app/View/Controller/underscored_function_name.ctp. By naming the pieces of your application using CakePHP conventions, you gain functionality without the hassle and maintenance tethers of configuration. Heres a final example that ties the conventions Database table: people Model class: Person, found at /app/Model/Person.php Controller class: PeopleController, found at /app/Controller/PeopleController.php View template, found at /app/View/People/index.ctp

Using these conventions, CakePHP knows that a request to http://example.com/people/ maps to a call on the index() function of the PeopleController, where the Person model is automatically available (and automatically tied to the people table in the database), and renders to a file. None of these relationships have been configured by any means other than by creating classes and files that youd need to create anyway.

Вам также может понравиться