Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

PSR-1 Coding Style Guide (multi-chapter) #15

Closed
wants to merge 28 commits into from

7 participants

@pmjones
Owner

Please examine this expanded style guide as a proposal for PSR-1. Consider it as a starting point for discussion, not a final document.

...-style-guide/0700-function-and-method-declarations.md
((13 lines not shown))
+
+ <?php
+ namespace Vendor\Package;
+ function fooBarBaz($arg1, $arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+All functions are namespaced; global functions are disallowed.
+
+Strongly consider using static class methods rather than functions; this will help support autoloading.
+
+Methods
+-------
+
+Class methods are always be prefixed with an explicit vsibility keyword:
@alganet
alganet added a note

Not sure about this. There are great projects (like SabreDAV) that doesn't make the public keyword explicit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@drak

Could you possibly format this commit a little with some linebreaks at 80-100ish characters? Makes it very difficult to read online otherwise and is the standard practice for text formats.

@alganet

PSR-0 was great 'cause almost every major project was already using it. We just documented a pre-existing behavior to make it official. I believe the best standards are born this way.

I'm pretty sure we could find an already implemented common set of standards in different projects then build a PSR-1 on top of that.

@pmjones
Owner

@drak: Yes, I will break them around 80. Thanks for pointing it out.

@pmjones
Owner

@alganet: This is mostly a common set of standards implemented across Horde, PEAR, PEAR-compliant but not PEAR-accepted project, Solar and projects derived from it, Zend and projects derived from it, Aura, and others. The central PEAR standards are the most mature in PHP land, and my guess is the most widely-distributed in the sense of being used in disparate projects.

pmjones added some commits
@pmjones pmjones break lines at about 80 chars 0335b99
@pmjones pmjones merge spelling changes 7bb84cd
@pmjones pmjones update line length notes per Andreas Moller and Wil Moore 49b6fef
@pmjones pmjones add a note about namespace names, and change so that there is one 'us…
…e' per line, instead of one 'use' and multiple lines (per gnugat)
c36244b
@pmjones pmjones add a note about namespace names, and change so that there is one 'us…
…e' per line, instead of one 'use' and multiple lines (per gnugat) ... also remove prefix/suffix requirements, per discssion with klaussilveira
5aa80a2
@pmjones pmjones Merge branch 'master' of github.com:pmjones/fig-standards 3c5dea0
@pmjones pmjones use namespaced constants, per @KingCrunch, and only use globals const…
…ants as a fallback
aecd965
@pmjones pmjones per notes from @gnugat and Wil Moore III, discourage global vars inst…
…ead of disallowing
93e6c5b
@pmjones pmjones per notes from @KingCrunch and @klaussilveira, reducing the errors ch…
…apter to say only E_ALL
9cd5072
@pmjones pmjones add try/catch to the control structures c6a7158
@pmjones pmjones rename the chapter 336336b
@pmjones pmjones add a comma 97003b0
@pmjones pmjones minor changes c775d79
@pmjones pmjones update the 'credits' aac843f
@pmjones pmjones add note about trailing space d4b4c3d
@pmjones pmjones discourage, but allow, global functions fa5e0ba
@pmjones pmjones extract operator and expression rules to their own chapter ee14d0b
@pmjones pmjones add <?php lines e977d3e
@pmjones pmjones minor updates 41c3ae5
@pmjones pmjones break into sections, add a note about blank lines e2bb63d
@pmjones pmjones rewording 214b6a3
@pmjones pmjones rewording 9412f14
@pmjones pmjones rewording cad7314
@pmjones pmjones include a reference to &$args f51cce2
@pmjones pmjones fix a merge conflict, and some rewording 67af4d0
@pmjones
Owner

Closing to make a new pull request with changes from comments above.

@pmjones pmjones closed this
@drak drak commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((16 lines not shown))
+ include "path/to/file.php";
+
+Class files should not use `include` (et al.) to load other classes; let the
+autoloader load the classes as needed.
+
+
+`if`, `elseif`, `else`
+----------------------
+
+An `if` statement looks like the following. Note the placement of parentheses,
+spaces, and braces:
+
+ <?php
+ if ($expression1 || ($expression2 && $expression3)) {
+ echo "First case";
+ } elseif (! $expression4 && ! $expression5) {
@drak
drak added a note

Isn't else if more readable?

@drak
drak added a note

Can we please have ! next to the expression that is negated without a space? It's very strange otherwise.

@pmjones Owner
pmjones added a note

I reviewed the codebases of ZF, Symfony, CI, and others. Even in the same projects, I see mixes of "else if" and "elseif" (which I didn't really expect). I don't think else if with the space is more readable; I think it's as readable. I'd also argue that saving a space might be important because of line line length, but it's probably not that important. Maybe the guide could read "whichever you use, use it consistently throughout the project."

@pmjones Owner
pmjones added a note

Regarding !, all the other operators have a space between them. The only ones that don't are the increment/decrement operators; they actually change the value of the variable involved, so their behavior seems different enough to warrant a modified style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@drak drak commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((54 lines not shown))
+ if ($value) {
+ echo "True";
+ }
+
+
+`switch`, `case`
+----------------
+
+A switch statement looks like the following. Note the placement of
+parentheses, spaces, and braces; the indent levels for `case` and `break`
+statements; and the presence of a `// no break` comment when a break is
+intentionally omitted.
+
+ <?php
+ switch ($expression) {
+
@drak
drak added a note

Are the extra line breaks here intentional?

@pmjones Owner
pmjones added a note

Good point: yes, they're "intentional" but they're not part of the requirement. Extra whitespace makes for easier reading sometimes. I'll remove them and see how it looks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@drak drak commented on the diff
...-coding-style-guide/0200-indenting-and-line-length.md
@@ -0,0 +1,45 @@
+Indenting and Line Length
+=========================
+
+Indenting
+---------
+
+Use an indent of 4 spaces. Do not use tabs. The use of spaces helps to avoid
+problems with diffs, patches, history, and annotations, and provides
+fine-grained sub-indentation when aligning elements on consecutive lines.
+
+Line Length
+-----------
+
+Lines should be limited to 75-85 characters in length. This is based on known
@drak
drak added a note

I'm not so sure this is good for code. This particular limit was popular when screen sizes were smaller, but now screens and resolutions are much bigger and 100 quite acceptable. This is something that is more appropriate for text files (like markdown or rst).

@pmjones Owner
pmjones added a note

Horde, PEAR, Solar, Symfony, Zend, Lithium, et al. all note 80 characters as the expected line length (in some cases it's a soft limit, but it's still mentioned). Per comments elsewhere, screen size and resolution are not the driving factor; human cognitive limitations are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/0100-php-tags.md
@@ -0,0 +1,9 @@
+PHP Tags
+========
+
+Use the long `<?php ?>` tags for PHP code. Use of short-echo `<?= ?>` tags is
+also allowed. Do not use the other tag variations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/0100-php-tags.md
@@ -0,0 +1,9 @@
+PHP Tags
+========
+
+Use the long `<?php ?>` tags for PHP code. Use of short-echo `<?= ?>` tags is
+also allowed. Do not use the other tag variations.
+
+Cf. <http://php.net/manual/en/language.basic-syntax.phpmode.php>
+
+In files that contain only PHP, leave out the closing PHP tag.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0200-indenting-and-line-length.md
@@ -0,0 +1,45 @@
+Indenting and Line Length
+=========================
+
+Indenting
+---------
+
+Use an indent of 4 spaces. Do not use tabs. The use of spaces helps to avoid
+problems with diffs, patches, history, and annotations, and provides
+fine-grained sub-indentation when aligning elements on consecutive lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0200-indenting-and-line-length.md
((21 lines not shown))
+> How many words per line can a person scan, and still be able to grasp the
+> content of the line in the context of the surrounding lines? Printing and
+> publishing typographers figured out a long time ago that most people can
+> read no more than 10 to 12 words per line before they have trouble
+> differentiating lines from each other. (A “word” is counted as five
+> characters on average.) Even allowing for a 25% to 50% increase, that
+> brings us up to 15 words. Times 5 characters per word, that means 75
+> characters on a line.
+>
+> So the style guide limitation on line length is not exactly arbitrary. It
+> is about the developer’s ability to effectively scan and comprehend
+> strings of text, not about the technical considerations of terminals and
+> text-editors.
+
+-- "Line Length, Volume, and Density"
+ <http://paul-m-jones.com/archives/276>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0200-indenting-and-line-length.md
((28 lines not shown))
+> characters on a line.
+>
+> So the style guide limitation on line length is not exactly arbitrary. It
+> is about the developer’s ability to effectively scan and comprehend
+> strings of text, not about the technical considerations of terminals and
+> text-editors.
+
+-- "Line Length, Volume, and Density"
+ <http://paul-m-jones.com/archives/276>
+
+
+Other Considerations
+--------------------
+
+Code blocks may have as many blank lines as needed to increase readability
+and comprehension.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0200-indenting-and-line-length.md
((30 lines not shown))
+> So the style guide limitation on line length is not exactly arbitrary. It
+> is about the developer’s ability to effectively scan and comprehend
+> strings of text, not about the technical considerations of terminals and
+> text-editors.
+
+-- "Line Length, Volume, and Density"
+ <http://paul-m-jones.com/archives/276>
+
+
+Other Considerations
+--------------------
+
+Code blocks may have as many blank lines as needed to increase readability
+and comprehension.
+
+Do not add trailing spaces at the end of lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-1-coding-style-guide/0300-namespace-use-and-class.md
@@ -0,0 +1,54 @@
+`namespace`, `use`, and `class`
+===============================
+
+All namespaces and classes should be named with PSR-0 in mind. This means each
+class should be in a file by itself, and should be in a namespace of at least
+two levels: a top-level vendor name, and a second-level package name within
+that vendor.
@Seldaek
Seldaek added a note

This is not right. As far as I know the second level namespace is not enforced by PSR-0, and many many libs out there just have a vendor name namespace containing core classes. The key thing is that you don't have anything in the global namespace to avoid collisions & improve autoload-ability with prefixes.

@pmjones Owner
pmjones added a note

Wow, you're right. All the examples have Vendor\Package, but the actual "Mandatory" bullet point only says "Vendor." Good catch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-1-coding-style-guide/0300-namespace-use-and-class.md
((13 lines not shown))
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ // constants, properties, methods
+ }
+
+The `use` declarations go immediately after the namespace declaration with no
+line separating them. There should be one `use` keyword per declaration.
+
+ <?php
+ namespace Vendor\Package;
+ use FooClass;
+ use BarClass as Bar;
+ use OtherVendor\OtherPackage\BazClass;

:thumbsup:

Makes a lot of sense to me (for the same reasons I propose wrapping of method call parameters and array initialization with a trailing comma on the last line before a line followed with );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-1-coding-style-guide/0300-namespace-use-and-class.md
((23 lines not shown))
+
+ <?php
+ namespace Vendor\Package;
+ use FooClass;
+ use BarClass as Bar;
+ use OtherVendor\OtherPackage\BazClass;
+
+ class ClassName
+ {
+ // constants, properties, methods
+ }
+
+The `extends` and `implements` keywords should be on the same line as the
+class name. Lists of `implements` that exceed the line length limit may be
+split across multiple lines, where each subsequent line is indented once.
+List only one interface per line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/0400-constants.md
@@ -0,0 +1,29 @@
+Constants
+=========
+
+The PHP keywords `true`, `false`, and `null` are all lower case all the time.
+
+All other user-defined constants are all upper case all the time, with
+underscore separators.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/0400-constants.md
@@ -0,0 +1,29 @@
+Constants
+=========
+
+The PHP keywords `true`, `false`, and `null` are all lower case all the time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/0400-constants.md
((3 lines not shown))
+
+The PHP keywords `true`, `false`, and `null` are all lower case all the time.
+
+All other user-defined constants are all upper case all the time, with
+underscore separators.
+
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ const CONSTANT_NAME = 'constant value';
+ }
+
+Global constants are strongly discouraged. Instead, create namespaced
+constants for the vendor and package:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...oding-style-guide/0500-variable-and-property-names.md
@@ -0,0 +1,32 @@
+Variable And Property Names
+===========================
+
+This guide expressly avoids any requirement regarding the use of
+`$StudlyCase`, `$camelCase`, or `$under_score` variable and property names. It
+is often the case that variable names map directly field names in external
+data sources. Changing between naming conventions when changing contexts
+merely to suit a style guide would be counterproductive in such cases.
+
+Some projects prefix property names with a single underscore to indicate a
+protected or private visibility. This guide discourages but does not disallow
+that practice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...oding-style-guide/0500-variable-and-property-names.md
((1 lines not shown))
+Variable And Property Names
+===========================
+
+This guide expressly avoids any requirement regarding the use of
+`$StudlyCase`, `$camelCase`, or `$under_score` variable and property names. It
+is often the case that variable names map directly field names in external
+data sources. Changing between naming conventions when changing contexts
+merely to suit a style guide would be counterproductive in such cases.
+
+Some projects prefix property names with a single underscore to indicate a
+protected or private visibility. This guide discourages but does not disallow
+that practice.
+
+Whatever naming convention is used should be applied consistently within a
+reasonable scope. That scope may be vendor-level, package-level, class-level,
+or function-level.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0600-variable-and-property-assignment.md
((14 lines not shown))
+ $short = fooBar($baz);
+ $longer = dibGir($zim);
+
+
+Multi-Line Assignment
+---------------------
+
+Assignments may be split onto several lines when the line length limit is
+exceeded. The equals sign has to be positioned onto the following line, and
+indented once.
+
+ $this->longArrayPropertyName[$this->someOtherPropertyValue]
+ = $object->getFunctionResult(ClassName::CONSTANT_VALUE);
+
+Similarly, when concatenating strings across multiple lines, align the dot
+operator with the equals:

:hand:

I'm not sure whether that's a great idea, Paul. I've done this in the past, too, and I liked it a lot, but when you start refactoring code it requires you to shift around a lot of lines, and if in bad luck, it's not done with a few tabs (of course, interpreted as 4 spaces). What do you think about indenting concatenation with 4 spaces?

$foo = 'prefix_string '
    . $object->getSomeStringResult()
    . ' suffix string'
;
@pmjones Owner
pmjones added a note

What you suggest is what PEAR recommends, but ZF recommends aligning on the equals. After having used both, and after talking with others about it, we have found it easier when reading code to look down a single "column" of concatenation (i.e., when aligned on the equals). Does it cause editing troubles? Yes, but only when you change the length of the variable name. I think the tradeoff for aligning on equals is reasonable here.

I agree with @pmjones, readability > writability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0600-variable-and-property-assignment.md
((31 lines not shown))
+ $foo = 'prefix string '
+ . $object->getSomeStringResult()
+ . ' suffix string';
+
+ $bar .= 'prefix string '
+ . $object->getSomeStringResult()
+ . ' suffix string';
+
+
+Ternary Assignment
+------------------
+
+Ternary assignments may be split onto subsequent lines when the exceed the
+line length limit, or when the would be more readable. Align the question mark
+and colon with the equals sign.
+

:hand:

See my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0600-variable-and-property-assignment.md
((45 lines not shown))
+and colon with the equals sign.
+
+ $foo = ($expression1 && $expression2)
+ ? $foo
+ : $bar;
+
+ $bar = ($expression3 && $expression4)
+ ? $a_very_long_variable_name
+ : $bar;
+
+
+Assignment By Reference
+-----------------------
+
+When assigning by reference, the `&` should be attached to the variable, not
+the operator:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0600-variable-and-property-assignment.md
((61 lines not shown))
+
+ // incorrect
+ $foo =& $bar;
+
+ // correct
+ $foo = &$bar;
+
+
+Array Assignment
+----------------
+
+Array assignments may be split across subsequent lines if they would otherwise
+break the line length limit, or if it would improve readability. They should be
+indented once per array, and should be aligned on the `=>` double arrow. The
+last value in each array should have a trailing comma; this is valid syntax
+and reduces the chance of syntax violations when adding new elements.

:thumbsup:

Trailing comma.

:hand:

Alignment with the =>arrow wastes some time with adding spaces that's otherwise spent more wisely. I'm also not sure whether readability is increased when you have (for other reasons) some really, really long array keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
@@ -0,0 +1,90 @@
+Function And Method Declarations
+================================
+
+Function and method names are in `camelCase`.
+
+Some projects prefix function and method names with a single underscore to
+indicate a protected or private visibility. This guide discourages but does
+not disallow that practice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
@@ -0,0 +1,90 @@
+Function And Method Declarations
+================================
+
+Function and method names are in `camelCase`.
+
+Some projects prefix function and method names with a single underscore to
+indicate a protected or private visibility. This guide discourages but does
+not disallow that practice.
+
+
+Functions
+---------
+
+A function declaration looks like the following. Note the placement of
+parentheses, commas, spaces, and braces:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
((14 lines not shown))
+A function declaration looks like the following. Note the placement of
+parentheses, commas, spaces, and braces:
+
+ <?php
+ namespace Vendor\Package;
+
+ function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+This guide encourages using static class methods rather than functions; doing
+so helps to support autoloading.
+
+Global functions are strongly discouraged. If a global function is
+unavoidable, prefix it with the vendor and package name.

:+1:

I believe that it's always avoidable, as it could be refactored into a static method of a FooUtils class, for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
((26 lines not shown))
+so helps to support autoloading.
+
+Global functions are strongly discouraged. If a global function is
+unavoidable, prefix it with the vendor and package name.
+
+ <?php
+ function Vendor_Package_FunctionName()
+ {
+ // function body
+ }
+
+
+Methods
+-------
+
+Class methods are always be prefixed with an explicit visibility keyword:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
((34 lines not shown))
+ // function body
+ }
+
+
+Methods
+-------
+
+Class methods are always be prefixed with an explicit visibility keyword:
+
+ <?php
+ public function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+Static methods always have the `static` keyword before the visibility keyword:

:hand:

I've always felt visibility is of higher importance, therefore I suggest to have the static keyword follow the visibility keyword.

On the other hand, it's not something I couldn't get used too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-style-guide/0700-function-and-method-declarations.md
((46 lines not shown))
+ // function body
+ }
+
+Static methods always have the `static` keyword before the visibility keyword:
+
+ <?php
+ static public function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+
+Arguments
+---------
+
+Arguments with default values always go at the end of the argument list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0800-function-and-method-calls.md
((8 lines not shown))
+
+A method call looks identical:
+
+ $object->foo($bar, $baz, $dib);
+
+To support readability, parameters in subsequent calls to the same function or
+method may be aligned by parameter:
+
+ $object->foo('value1', 'foo', true);
+ $object->foo('another value', 'barbaz', false);
+ $object->foo('third', 'dib', true);
+
+If a function or method call exceeds the line length limit, or if it would
+improve readability, split parameters onto several lines. Each line should
+have only one parameter and should be indented once. The closing parenthesis
+goes on its own line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0800-function-and-method-calls.md
((16 lines not shown))
+ $object->foo('value1', 'foo', true);
+ $object->foo('another value', 'barbaz', false);
+ $object->foo('third', 'dib', true);
+
+If a function or method call exceeds the line length limit, or if it would
+improve readability, split parameters onto several lines. Each line should
+have only one parameter and should be indented once. The closing parenthesis
+goes on its own line.
+
+ $this->firstObject->secondObject->aFunctionWithAVeryLongName(
+ $value1,
+ $value2,
+ $value3
+ );
+
+The same applies to nested function calls and arrays.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0800-function-and-method-calls.md
((35 lines not shown))
+ $another->someEvenOtherFunc(
+ 'A string',
+ [
+ 'foo' => 'bar',
+ 'baz' => 'dib',
+ ],
+ 42
+ ),
+ $support->someEvenOtherFunc()
+ ),
+ $this->atLast(88)
+ );
+
+Using a fluent API may lead to several function calls on the same object in a
+row. Split subsequent calls onto separate lines; indent the subsequent lines
+to align the "->" arrows.

:hand:

See my comment.

Especially note the position of the comma, too.

$object
    ->foo('value1', 'value2')   
    ->bar(42, 88)
    ->baz()
;

Or even better (see my comment, can't seem to link to a line of your code):

$object
    ->foo(
        'value1', 
        'value2'
    )
    ->bar(
        42, 
        88
    )
    ->baz()
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0800-function-and-method-calls.md
((45 lines not shown))
+ $this->atLast(88)
+ );
+
+Using a fluent API may lead to several function calls on the same object in a
+row. Split subsequent calls onto separate lines; indent the subsequent lines
+to align the "->" arrows.
+
+ $object->foo('value1', 'value2')
+ ->bar(42, 88)
+ ->baz();
+
+When instantiating a class, if the constructor for that class has no
+parameters, omit the `()` from the instantiation.
+
+ $obj1 = new ClassWithConstructorParams($foo, $bar);
+ $obj2 = new ClassWithoutAnyConstructorParams;

:-1:

For omitting the () when a constructor doesn't take any parameters.

It might be a personal preference, but the () has some significance (at least to me) in terms of readability.

@drak
drak added a note

Also :-1: from me as this makes the code less readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@Seldaek Seldaek commented on the diff
proposed/psr-1-coding-style-guide/0000-preamble.md
((6 lines not shown))
+reference for reasonable expectations so as to reduce cognitive friction when
+scanning code from different projects.
+
+This style guide is not a moral or ethical statement. It is an attempt to
+agree upon a common set of rules, requirements, recommendations, idioms, and
+approaches for code formatting. Any such guide is by nature arbitrary. The
+benefit is in the adherence to the rules, not in the rules themselves.
+
+There are times when a particular rule or recommendation will not make sense
+in a particular limited context. Breaking the rule or recommendation in that
+particular limited context does not mean the remainder of the codebase under
+consideration is not PSR-1 compliant; instead, it is to be recognized as a
+regrettable but necessary departure from the guide for that one circumstance.
+
+This guide is derived from commonalities between Horde, PEAR, Solar, Symfony,
+Zend, and other projects.
@Seldaek
Seldaek added a note

Please use Zend Framework or ZF.

@pmjones Owner
pmjones added a note

Good call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
@@ -0,0 +1,187 @@
+Control Structures
+==================
+
+
+`include`, `include_once`, `require`, `require_once`
+----------------------------------------------------
+
+The `include` (et al.) structures are keywords, not functions. Do not use
+parentheses around the filename.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@drak drak commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((1 lines not shown))
+Control Structures
+==================
+
+
+`include`, `include_once`, `require`, `require_once`
+----------------------------------------------------
+
+The `include` (et al.) structures are keywords, not functions. Do not use
+parentheses around the filename.
+
+ <?php
+ // incorrect
+ include("/path/to/file.php");
+
+ // correct
+ include "path/to/file.php";
@drak
drak added a note

Should always use single quotes unless you need evaluation of variables in a string . e.g. echo "hello $name";

:+1:

For the enforcement of single quotes.

@pmjones Owner
pmjones added a note

Good call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((4 lines not shown))
+
+`include`, `include_once`, `require`, `require_once`
+----------------------------------------------------
+
+The `include` (et al.) structures are keywords, not functions. Do not use
+parentheses around the filename.
+
+ <?php
+ // incorrect
+ include("/path/to/file.php");
+
+ // correct
+ include "path/to/file.php";
+
+Class files should not use `include` (et al.) to load other classes; let the
+autoloader load the classes as needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@drak drak referenced this pull request
Closed

Updated PSR-1 expansion #16

@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((11 lines not shown))
+ <?php
+ // incorrect
+ include("/path/to/file.php");
+
+ // correct
+ include "path/to/file.php";
+
+Class files should not use `include` (et al.) to load other classes; let the
+autoloader load the classes as needed.
+
+
+`if`, `elseif`, `else`
+----------------------
+
+An `if` statement looks like the following. Note the placement of parentheses,
+spaces, and braces:

:hand:

I can think of a case where you have a large number of expressions - shouldn't there be some wrapping allowed?

On the other hand, these could be refactored (see Fowler, Martin. 1999. Refactoring - Improving the Design of Existing Code. Addison Wesley).

@pmjones Owner
pmjones added a note

Exactly -- some of these rules (not all of them, but some) end up being indicators that a refactor might be wise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((24 lines not shown))
+
+An `if` statement looks like the following. Note the placement of parentheses,
+spaces, and braces:
+
+ <?php
+ if ($expression1 || ($expression2 && $expression3)) {
+ echo "First case";
+ } elseif (! $expression4 && ! $expression5) {
+ echo "Second case";
+ } else {
+ echo "Default case";
+ }
+
+Always use braces to enclose the body of the statements. This standardizes
+how they look and reduces the likelihood of introducing errors as new lines
+get added to the body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((28 lines not shown))
+ <?php
+ if ($expression1 || ($expression2 && $expression3)) {
+ echo "First case";
+ } elseif (! $expression4 && ! $expression5) {
+ echo "Second case";
+ } else {
+ echo "Default case";
+ }
+
+Always use braces to enclose the body of the statements. This standardizes
+how they look and reduces the likelihood of introducing errors as new lines
+get added to the body.
+
+Do not perform variable assignment within `if` or `elseif` expressions. This
+reduces the difficulty of determining if the intent was to assign or to check
+equivalence. For example, this ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((71 lines not shown))
+ echo "First case";
+ break;
+
+ case 2:
+ echo "Second case";
+ // no break
+
+ default:
+ echo "Default case";
+ break;
+
+ }
+
+Do not perform variable assignment within `switch` expressions. This reduces
+the difficulty of determining if the intent was to assign or to check
+equivalence. For example, this ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((90 lines not shown))
+ // ...
+ }
+
+... should be replaced with this, to clarify the intent:
+
+ $value = foo();
+ switch ($value) {
+ // ...
+ }
+
+
+`while`, `do while`
+-------------------
+
+A `while` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((98 lines not shown))
+ }
+
+
+`while`, `do while`
+-------------------
+
+A `while` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
+
+ <?php
+ while ($expression) {
+ echo "Expression is true";
+ }
+
+Similarly, a `do while` statement looks like the following. Note the placement
+of parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((107 lines not shown))
+ <?php
+ while ($expression) {
+ echo "Expression is true";
+ }
+
+Similarly, a `do while` statement looks like the following. Note the placement
+of parentheses, spaces, and braces.
+
+ <?php
+ do {
+ echo "Expression is true";
+ } while ($expression);
+
+Always use braces to enclose the body of the statement. This standardizes how
+it looks and reduces the likelihood of introducing errors as new lines get
+added to the body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((116 lines not shown))
+ do {
+ echo "Expression is true";
+ } while ($expression);
+
+Always use braces to enclose the body of the statement. This standardizes how
+it looks and reduces the likelihood of introducing errors as new lines get
+added to the body.
+
+It is acceptable to perform assignment within `while` expressions.
+
+
+`for`
+-----
+
+A `for` statement looks like the following. Note the placement of parentheses,
+spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((130 lines not shown))
+A `for` statement looks like the following. Note the placement of parentheses,
+spaces, and braces.
+
+ <?php
+ for ($i = 0; $i < 10; $i++) {
+ echo $i;
+ }
+
+It is acceptable to perform assignment within `for` expressions.
+
+
+`foreach`
+---------
+
+A `foreach` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((142 lines not shown))
+---------
+
+A `foreach` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
+
+ <?php
+ foreach ($iterable as $key => $value) {
+ echo $key;
+ }
+
+
+`try`, `catch`
+--------------
+
+A `try catch` block looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...d/psr-1-coding-style-guide/0900-control-structures.md
((166 lines not shown))
+ }
+
+Always use braces to enclose the body of the statements. This standardizes
+how they look and reduces the likelihood of introducing errors as new lines
+get added to the body.
+
+Interweaving Non-PHP Output
+---------------------------
+
+Interweaving PHP and non-PHP using braces is discouraged:
+
+ <?php if ($is_true) { ?>
+ direct output
+ <?php } ?>
+
+Instead, use the alternative syntax for control structures:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
@@ -0,0 +1,74 @@
+Operators and Expressions
+=========================
+
+Operators
+---------
+
+Operators should have one space before and after. Opening parentheses have no
+space after, and closing parentheses have no space before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
((1 lines not shown))
+Operators and Expressions
+=========================
+
+Operators
+---------
+
+Operators should have one space before and after. Opening parentheses have no
+space after, and closing parentheses have no space before.
+
+ <?php
+ $a = ($b + $c) * ($d / ($e - $f));
+ $foo = $bar . $baz;
+ $zim = $gir && $irk;
+
+The `!` operator should have a space between it and the expression it is
+negating.

:+1:

Increases readability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
((8 lines not shown))
+space after, and closing parentheses have no space before.
+
+ <?php
+ $a = ($b + $c) * ($d / ($e - $f));
+ $foo = $bar . $baz;
+ $zim = $gir && $irk;
+
+The `!` operator should have a space between it and the expression it is
+negating.
+
+ <?php
+ if (! $object instanceof $class) {
+ // ...
+ }
+
+Increment/decrement operators should have no space separation:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
((14 lines not shown))
+
+The `!` operator should have a space between it and the expression it is
+negating.
+
+ <?php
+ if (! $object instanceof $class) {
+ // ...
+ }
+
+Increment/decrement operators should have no space separation:
+
+ <?php
+ $i--;
+ ++$k;
+
+Casts should have a space between the type and the variable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
((26 lines not shown))
+ $i--;
+ ++$k;
+
+Casts should have a space between the type and the variable.
+
+ <?php
+ $foo = (bool) $bar;
+
+
+Expressions
+-----------
+
+Expressions for `if`, `switch`, etc. statements should fit on one line. If the
+expression cannot fit on one line, extract the expression into an explaining
+variable and use that variable as the expression. For example, the following
+long expression ...

:+1:

Forget my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...-coding-style-guide/0950-operators-and-expressions.md
((45 lines not shown))
+ || $expression3 || $expression4) {
+ // perform some action
+ }
+
+... should be rewritten as:
+
+ <?php
+ $set1 = $expression1 && $expression2 && veryLongFunctionName();
+ if ($set1 || $expression3 || $expression4) {
+ // perform some action
+ }
+
+If the set of expressions still cannot fit on one line, or if it would improve
+readability, split the expression onto several subsequent lines at the `&&`
+and `||` operators. Operators should align with the equals sign so that the
+expressions themselves are also aligned.

:-1:

Alignment, see my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
...osed/psr-1-coding-style-guide/1000-error-reporting.md
@@ -0,0 +1,7 @@
+Error Reporting
+===============
+
+PHP code must not emit notices, warnings, or errors under `E_ALL` error
+reporting. This is because certain styles are parsed and executed (such as
+undeclared variables, unquoted strings, etc.) but still show up as notices.
+Coding with `E_ALL` turned on forces a consistent technical style.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/1100-comments.md
@@ -0,0 +1,46 @@
+Comments and DocBlocks
+======================
+
+This guide recognizes that different projects have different documentation
+tools and requirements. In the absence of project-specific requirements,
+documentation should follow the standard set out by PHPDocumentor, DocBlox,
+etc.
+
+Class files should have at least two sets of documentation blocks: a
+file-level block above the namespace declaration, and a class-specific block
+above the class declaration.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/1100-comments.md
((21 lines not shown))
+ *
+ */
+ namespace Vendor\Package;
+
+ /**
+ *
+ * This is a class-level documentation block.
+ *
+ */
+ class ClassName
+ {
+ // class body
+ }
+
+This guide strongly encourages the documentation of each constant, property,
+method, method argument, and thrown exception in each class file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/1100-comments.md
((28 lines not shown))
+ *
+ */
+ class ClassName
+ {
+ // class body
+ }
+
+This guide strongly encourages the documentation of each constant, property,
+method, method argument, and thrown exception in each class file.
+
+This guide strongly encourages non-documentation comments as well, if only as
+a tool to aid in comprehension of the code being commented on.
+(Self-commenting code is frequently so only for the original author.)
+
+Comments should use only the `/* */` and `//` style. Do not use the `#`
+commenting style.

:+1:

Also, I think it's important for auto-completion to provide comments such as

/* @var $fooService \Application\Service\Foo */
$fooService = $this->getService('Foo');

when the PhpDoc-umented return values don't tell for sure what class of object is returned (because the object, for example, is a concrete implementation of an abstract class or an interface).

/**
 * Attempts to retrieve a service with the specified name.
 * 
 * @param  string $name
 * @return \Application\Service\ServiceAbstract
 */
protected function getService($name = null)
{
    /* stuff happens*/
    return $service;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/1100-comments.md
((31 lines not shown))
+ {
+ // class body
+ }
+
+This guide strongly encourages the documentation of each constant, property,
+method, method argument, and thrown exception in each class file.
+
+This guide strongly encourages non-documentation comments as well, if only as
+a tool to aid in comprehension of the code being commented on.
+(Self-commenting code is frequently so only for the original author.)
+
+Comments should use only the `/* */` and `//` style. Do not use the `#`
+commenting style.
+
+Use `example.com`, `example.org`, and `example.net` for all example domain
+names in documentation.

:+1:

For reference, see RFC 2606.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@localheinz localheinz commented on the diff
proposed/psr-1-coding-style-guide/1100-comments.md
((25 lines not shown))
+ /**
+ *
+ * This is a class-level documentation block.
+ *
+ */
+ class ClassName
+ {
+ // class body
+ }
+
+This guide strongly encourages the documentation of each constant, property,
+method, method argument, and thrown exception in each class file.
+
+This guide strongly encourages non-documentation comments as well, if only as
+a tool to aid in comprehension of the code being commented on.
+(Self-commenting code is frequently so only for the original author.)

:+1:

But also bear in mind Fowler, Martin. 1999. Refactoring - Improving the Design of Existing Code. Addison Wesley, where Fowler says that comments should explain the why and not the what. Use refactoring to improve the code. Code should tell a story to the reader, not the comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@clemherreman clemherreman commented on the diff
...-1-coding-style-guide/0300-namespace-use-and-class.md
((7 lines not shown))
+that vendor.
+
+Class names are always in `StudlyCase`. The class declaration should have one
+empty line above it. The opening and closing braces for the class go on their
+own line.
+
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ // constants, properties, methods
+ }
+
+The `use` declarations go immediately after the namespace declaration with no
+line separating them. There should be one `use` keyword per declaration.

Why shouldn't it be no lines separating them ? It may improve readability to regroup the use by vendor name, separated by a line.

@pmjones Owner
pmjones added a note

@clemherreman Others have argued, and I now agree, that namespace, use, and class should all have a line of separation.

I wouldn't say "should", but "may" :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 6, 2012
  1. @pmjones
  2. @saltybeagle
  3. @pmjones

    Merge pull request #1 from saltybeagle/master

    pmjones authored
    Minor spelling corrections
Commits on Mar 7, 2012
  1. @pmjones

    break lines at about 80 chars

    pmjones authored
  2. @pmjones

    merge spelling changes

    pmjones authored
Commits on Mar 8, 2012
  1. @pmjones
  2. @pmjones

    add a note about namespace names, and change so that there is one 'us…

    pmjones authored
    …e' per line, instead of one 'use' and multiple lines (per gnugat)
  3. @pmjones

    add a note about namespace names, and change so that there is one 'us…

    pmjones authored
    …e' per line, instead of one 'use' and multiple lines (per gnugat) ... also remove prefix/suffix requirements, per discssion with klaussilveira
  4. @pmjones
  5. @pmjones
  6. @pmjones
  7. @pmjones

    per notes from @KingCrunch and @klaussilveira, reducing the errors ch…

    pmjones authored
    …apter to say only E_ALL
  8. @pmjones
  9. @pmjones

    rename the chapter

    pmjones authored
  10. @pmjones

    add a comma

    pmjones authored
  11. @pmjones

    minor changes

    pmjones authored
  12. @pmjones

    update the 'credits'

    pmjones authored
  13. @pmjones

    add note about trailing space

    pmjones authored
  14. @pmjones
  15. @pmjones
  16. @pmjones

    add <?php lines

    pmjones authored
  17. @pmjones

    minor updates

    pmjones authored
  18. @pmjones
  19. @pmjones

    rewording

    pmjones authored
  20. @pmjones

    rewording

    pmjones authored
  21. @pmjones

    rewording

    pmjones authored
  22. @pmjones

    include a reference to &$args

    pmjones authored
  23. @pmjones
This page is out of date. Refresh to see the latest.
View
21 proposed/psr-1-coding-style-guide/0000-preamble.md
@@ -0,0 +1,21 @@
+Preamble
+========
+
+The goal for this guide is to increase consistency in style across disparate
+PHP projects written by multiple authors. It is intended to serve as a
+reference for reasonable expectations so as to reduce cognitive friction when
+scanning code from different projects.
+
+This style guide is not a moral or ethical statement. It is an attempt to
+agree upon a common set of rules, requirements, recommendations, idioms, and
+approaches for code formatting. Any such guide is by nature arbitrary. The
+benefit is in the adherence to the rules, not in the rules themselves.
+
+There are times when a particular rule or recommendation will not make sense
+in a particular limited context. Breaking the rule or recommendation in that
+particular limited context does not mean the remainder of the codebase under
+consideration is not PSR-1 compliant; instead, it is to be recognized as a
+regrettable but necessary departure from the guide for that one circumstance.
+
+This guide is derived from commonalities between Horde, PEAR, Solar, Symfony,
+Zend, and other projects.
@Seldaek
Seldaek added a note

Please use Zend Framework or ZF.

@pmjones Owner
pmjones added a note

Good call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
View
9 proposed/psr-1-coding-style-guide/0100-php-tags.md
@@ -0,0 +1,9 @@
+PHP Tags
+========
+
+Use the long `<?php ?>` tags for PHP code. Use of short-echo `<?= ?>` tags is
+also allowed. Do not use the other tag variations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Cf. <http://php.net/manual/en/language.basic-syntax.phpmode.php>
+
+In files that contain only PHP, leave out the closing PHP tag.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
View
45 proposed/psr-1-coding-style-guide/0200-indenting-and-line-length.md
@@ -0,0 +1,45 @@
+Indenting and Line Length
+=========================
+
+Indenting
+---------
+
+Use an indent of 4 spaces. Do not use tabs. The use of spaces helps to avoid
+problems with diffs, patches, history, and annotations, and provides
+fine-grained sub-indentation when aligning elements on consecutive lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Line Length
+-----------
+
+Lines should be limited to 75-85 characters in length. This is based on known
@drak
drak added a note

I'm not so sure this is good for code. This particular limit was popular when screen sizes were smaller, but now screens and resolutions are much bigger and 100 quite acceptable. This is something that is more appropriate for text files (like markdown or rst).

@pmjones Owner
pmjones added a note

Horde, PEAR, Solar, Symfony, Zend, Lithium, et al. all note 80 characters as the expected line length (in some cases it's a soft limit, but it's still mentioned). Per comments elsewhere, screen size and resolution are not the driving factor; human cognitive limitations are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+human cognitive limitations, not the technical limitations of screen windows
+or text editors. When necessary, it is allowed to split a single statement
+across subsequent lines, per rules noted elsewhere in this guide.
+
+Some further insight into the 75-85 characters rule:
+
+> How many words per line can a person scan, and still be able to grasp the
+> content of the line in the context of the surrounding lines? Printing and
+> publishing typographers figured out a long time ago that most people can
+> read no more than 10 to 12 words per line before they have trouble
+> differentiating lines from each other. (A “word” is counted as five
+> characters on average.) Even allowing for a 25% to 50% increase, that
+> brings us up to 15 words. Times 5 characters per word, that means 75
+> characters on a line.
+>
+> So the style guide limitation on line length is not exactly arbitrary. It
+> is about the developer’s ability to effectively scan and comprehend
+> strings of text, not about the technical considerations of terminals and
+> text-editors.
+
+-- "Line Length, Volume, and Density"
+ <http://paul-m-jones.com/archives/276>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+
+Other Considerations
+--------------------
+
+Code blocks may have as many blank lines as needed to increase readability
+and comprehension.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Do not add trailing spaces at the end of lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
View
54 proposed/psr-1-coding-style-guide/0300-namespace-use-and-class.md
@@ -0,0 +1,54 @@
+`namespace`, `use`, and `class`
+===============================
+
+All namespaces and classes should be named with PSR-0 in mind. This means each
+class should be in a file by itself, and should be in a namespace of at least
+two levels: a top-level vendor name, and a second-level package name within
+that vendor.
@Seldaek
Seldaek added a note

This is not right. As far as I know the second level namespace is not enforced by PSR-0, and many many libs out there just have a vendor name namespace containing core classes. The key thing is that you don't have anything in the global namespace to avoid collisions & improve autoload-ability with prefixes.

@pmjones Owner
pmjones added a note

Wow, you're right. All the examples have Vendor\Package, but the actual "Mandatory" bullet point only says "Vendor." Good catch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Class names are always in `StudlyCase`. The class declaration should have one
+empty line above it. The opening and closing braces for the class go on their
+own line.
+
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ // constants, properties, methods
+ }
+
+The `use` declarations go immediately after the namespace declaration with no
+line separating them. There should be one `use` keyword per declaration.

Why shouldn't it be no lines separating them ? It may improve readability to regroup the use by vendor name, separated by a line.

@pmjones Owner
pmjones added a note

@clemherreman Others have argued, and I now agree, that namespace, use, and class should all have a line of separation.

I wouldn't say "should", but "may" :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ namespace Vendor\Package;
+ use FooClass;
+ use BarClass as Bar;
+ use OtherVendor\OtherPackage\BazClass;

:thumbsup:

Makes a lot of sense to me (for the same reasons I propose wrapping of method call parameters and array initialization with a trailing comma on the last line before a line followed with );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ class ClassName
+ {
+ // constants, properties, methods
+ }
+
+The `extends` and `implements` keywords should be on the same line as the
+class name. Lists of `implements` that exceed the line length limit may be
+split across multiple lines, where each subsequent line is indented once.
+List only one interface per line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ namespace Vendor\Package;
+ use FooClass;
+ use BarClass as Bar;
+ use OtherVendor\OtherPackage\BazClass;
+
+ class ClassName extends ParentClass implements
+ InterfaceName,
+ AnotherInterfaceName,
+ YetAnotherInterface,
+ InterfaceInterface
+ {
+ // constants, properties, methods
+ }
+
View
29 proposed/psr-1-coding-style-guide/0400-constants.md
@@ -0,0 +1,29 @@
+Constants
+=========
+
+The PHP keywords `true`, `false`, and `null` are all lower case all the time.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+All other user-defined constants are all upper case all the time, with
+underscore separators.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ const CONSTANT_NAME = 'constant value';
+ }
+
+Global constants are strongly discouraged. Instead, create namespaced
+constants for the vendor and package:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ namespace Vendor\Package;
+ const CONSTANT_NAME = 'constant_value';
+
+If a global constant is absolutely unavoidable, prefix it with the vendor and
+package name:
+
+ <?php
+ define('VENDOR_PACKAGE_CONSTANT_NAME', 'constant_value');
+
View
32 proposed/psr-1-coding-style-guide/0500-variable-and-property-names.md
@@ -0,0 +1,32 @@
+Variable And Property Names
+===========================
+
+This guide expressly avoids any requirement regarding the use of
+`$StudlyCase`, `$camelCase`, or `$under_score` variable and property names. It
+is often the case that variable names map directly field names in external
+data sources. Changing between naming conventions when changing contexts
+merely to suit a style guide would be counterproductive in such cases.
+
+Some projects prefix property names with a single underscore to indicate a
+protected or private visibility. This guide discourages but does not disallow
+that practice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Whatever naming convention is used should be applied consistently within a
+reasonable scope. That scope may be vendor-level, package-level, class-level,
+or function-level.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Class properties should explicitly note the visibility keyword.
+
+ <?php
+ namespace Vendor\Package;
+
+ class ClassName
+ {
+ public $property = null;
+ }
+
+Global variables are strongly discouraged. If a global variable is absolutely
+unavoidable, it should be prefixed with the vendor and package name.
+
+ <?php
+ $Vendor_Package_VariableName = 'variable_value';
View
86 proposed/psr-1-coding-style-guide/0600-variable-and-property-assignment.md
@@ -0,0 +1,86 @@
+Variable and Property Assignment
+================================
+
+Single Assignment
+-----------------
+
+Assignment looks like the following.
+
+ $foo = 'value';
+
+To support readability, contiguous assignments may be aligned on the equals
+sign:
+
+ $short = fooBar($baz);
+ $longer = dibGir($zim);
+
+
+Multi-Line Assignment
+---------------------
+
+Assignments may be split onto several lines when the line length limit is
+exceeded. The equals sign has to be positioned onto the following line, and
+indented once.
+
+ $this->longArrayPropertyName[$this->someOtherPropertyValue]
+ = $object->getFunctionResult(ClassName::CONSTANT_VALUE);
+
+Similarly, when concatenating strings across multiple lines, align the dot
+operator with the equals:

:hand:

I'm not sure whether that's a great idea, Paul. I've done this in the past, too, and I liked it a lot, but when you start refactoring code it requires you to shift around a lot of lines, and if in bad luck, it's not done with a few tabs (of course, interpreted as 4 spaces). What do you think about indenting concatenation with 4 spaces?

$foo = 'prefix_string '
    . $object->getSomeStringResult()
    . ' suffix string'
;
@pmjones Owner
pmjones added a note

What you suggest is what PEAR recommends, but ZF recommends aligning on the equals. After having used both, and after talking with others about it, we have found it easier when reading code to look down a single "column" of concatenation (i.e., when aligned on the equals). Does it cause editing troubles? Yes, but only when you change the length of the variable name. I think the tradeoff for aligning on equals is reasonable here.

I agree with @pmjones, readability > writability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ $foo = 'prefix string '
+ . $object->getSomeStringResult()
+ . ' suffix string';
+
+ $bar .= 'prefix string '
+ . $object->getSomeStringResult()
+ . ' suffix string';
+
+
+Ternary Assignment
+------------------
+
+Ternary assignments may be split onto subsequent lines when the exceed the
+line length limit, or when the would be more readable. Align the question mark
+and colon with the equals sign.
+

:hand:

See my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ $foo = ($expression1 && $expression2)
+ ? $foo
+ : $bar;
+
+ $bar = ($expression3 && $expression4)
+ ? $a_very_long_variable_name
+ : $bar;
+
+
+Assignment By Reference
+-----------------------
+
+When assigning by reference, the `&` should be attached to the variable, not
+the operator:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ // incorrect
+ $foo =& $bar;
+
+ // correct
+ $foo = &$bar;
+
+
+Array Assignment
+----------------
+
+Array assignments may be split across subsequent lines if they would otherwise
+break the line length limit, or if it would improve readability. They should be
+indented once per array, and should be aligned on the `=>` double arrow. The
+last value in each array should have a trailing comma; this is valid syntax
+and reduces the chance of syntax violations when adding new elements.

:thumbsup:

Trailing comma.

:hand:

Alignment with the =>arrow wastes some time with adding spaces that's otherwise spent more wisely. I'm also not sure whether readability is increased when you have (for other reasons) some really, really long array keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ $an_array = [
+ 'foo' => 'bar',
+ 'subarray' => [
+ 'baz' => 'dib',
+ 'zim' => 'gir',
+ ],
+ 'irk' => 'doom',
+ ];
+
View
90 proposed/psr-1-coding-style-guide/0700-function-and-method-declarations.md
@@ -0,0 +1,90 @@
+Function And Method Declarations
+================================
+
+Function and method names are in `camelCase`.
+
+Some projects prefix function and method names with a single underscore to
+indicate a protected or private visibility. This guide discourages but does
+not disallow that practice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+
+Functions
+---------
+
+A function declaration looks like the following. Note the placement of
+parentheses, commas, spaces, and braces:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ namespace Vendor\Package;
+
+ function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+This guide encourages using static class methods rather than functions; doing
+so helps to support autoloading.
+
+Global functions are strongly discouraged. If a global function is
+unavoidable, prefix it with the vendor and package name.

:+1:

I believe that it's always avoidable, as it could be refactored into a static method of a FooUtils class, for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ function Vendor_Package_FunctionName()
+ {
+ // function body
+ }
+
+
+Methods
+-------
+
+Class methods are always be prefixed with an explicit visibility keyword:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ public function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+Static methods always have the `static` keyword before the visibility keyword:

:hand:

I've always felt visibility is of higher importance, therefore I suggest to have the static keyword follow the visibility keyword.

On the other hand, it's not something I couldn't get used too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ static public function fooBarBaz($arg1, &$arg2, $arg3 = [], $arg4 = null)
+ {
+ // function body
+ }
+
+
+Arguments
+---------
+
+Arguments with default values always go at the end of the argument list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Argument lists that exceed the line length limit may be split across
+subsequent indented lines. There is only one argument per line. The closing
+parenthesis and opening brace are placed together on their own line.
+
+ <?php
+ static public function fooBarBaz(
+ ClassTypeHint $arg1,
+ &$arg2,
+ array $arg3 = [],
+ $arg4 = null
+ ) {
+ // function body
+ }
+
+Anonymous Functions and Closures
+--------------------------------
+
+Declaration of anonymous functions looks like this; note the placement of
+parentheses, commas, spaces and braces:
+
+ $foo = function ($bar, $baz) use ($zim, $gir) {
+ // body of the function
+ };
+
+This is a departure from the "normal" function and method declaration. Because
+`function` is a keyword, it gets a space after it; the same is true for `use`.
+The opening brace goes on the same line as the declaration; the body is
+indented once; and the closing brace goes on its own outdented line.
View
61 proposed/psr-1-coding-style-guide/0800-function-and-method-calls.md
@@ -0,0 +1,61 @@
+Function And Method Calls
+=========================
+
+A function call looks like the following. Note the placement of parentheses,
+commas, and spaces:
+
+ foo($bar, $baz, $dib);
+
+A method call looks identical:
+
+ $object->foo($bar, $baz, $dib);
+
+To support readability, parameters in subsequent calls to the same function or
+method may be aligned by parameter:
+
+ $object->foo('value1', 'foo', true);
+ $object->foo('another value', 'barbaz', false);
+ $object->foo('third', 'dib', true);
+
+If a function or method call exceeds the line length limit, or if it would
+improve readability, split parameters onto several lines. Each line should
+have only one parameter and should be indented once. The closing parenthesis
+goes on its own line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ $this->firstObject->secondObject->aFunctionWithAVeryLongName(
+ $value1,
+ $value2,
+ $value3
+ );
+
+The same applies to nested function calls and arrays.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ $this->firstObject->secondObject->aFunctionWithAVeryLongName(
+ $object->someOtherFunc(
+ $another->someEvenOtherFunc(
+ 'A string',
+ [
+ 'foo' => 'bar',
+ 'baz' => 'dib',
+ ],
+ 42
+ ),
+ $support->someEvenOtherFunc()
+ ),
+ $this->atLast(88)
+ );
+
+Using a fluent API may lead to several function calls on the same object in a
+row. Split subsequent calls onto separate lines; indent the subsequent lines
+to align the "->" arrows.

:hand:

See my comment.

Especially note the position of the comma, too.

$object
    ->foo('value1', 'value2')   
    ->bar(42, 88)
    ->baz()
;

Or even better (see my comment, can't seem to link to a line of your code):

$object
    ->foo(
        'value1', 
        'value2'
    )
    ->bar(
        42, 
        88
    )
    ->baz()
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ $object->foo('value1', 'value2')
+ ->bar(42, 88)
+ ->baz();
+
+When instantiating a class, if the constructor for that class has no
+parameters, omit the `()` from the instantiation.
+
+ $obj1 = new ClassWithConstructorParams($foo, $bar);
+ $obj2 = new ClassWithoutAnyConstructorParams;

:-1:

For omitting the () when a constructor doesn't take any parameters.

It might be a personal preference, but the () has some significance (at least to me) in terms of readability.

@drak
drak added a note

Also :-1: from me as this makes the code less readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
View
187 proposed/psr-1-coding-style-guide/0900-control-structures.md
@@ -0,0 +1,187 @@
+Control Structures
+==================
+
+
+`include`, `include_once`, `require`, `require_once`
+----------------------------------------------------
+
+The `include` (et al.) structures are keywords, not functions. Do not use
+parentheses around the filename.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ // incorrect
+ include("/path/to/file.php");
+
+ // correct
+ include "path/to/file.php";
@drak
drak added a note

Should always use single quotes unless you need evaluation of variables in a string . e.g. echo "hello $name";

:+1:

For the enforcement of single quotes.

@pmjones Owner
pmjones added a note

Good call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Class files should not use `include` (et al.) to load other classes; let the
+autoloader load the classes as needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+
+`if`, `elseif`, `else`
+----------------------
+
+An `if` statement looks like the following. Note the placement of parentheses,
+spaces, and braces:

:hand:

I can think of a case where you have a large number of expressions - shouldn't there be some wrapping allowed?

On the other hand, these could be refactored (see Fowler, Martin. 1999. Refactoring - Improving the Design of Existing Code. Addison Wesley).

@pmjones Owner
pmjones added a note

Exactly -- some of these rules (not all of them, but some) end up being indicators that a refactor might be wise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ if ($expression1 || ($expression2 && $expression3)) {
+ echo "First case";
+ } elseif (! $expression4 && ! $expression5) {
@drak
drak added a note

Isn't else if more readable?

@drak
drak added a note

Can we please have ! next to the expression that is negated without a space? It's very strange otherwise.

@pmjones Owner
pmjones added a note

I reviewed the codebases of ZF, Symfony, CI, and others. Even in the same projects, I see mixes of "else if" and "elseif" (which I didn't really expect). I don't think else if with the space is more readable; I think it's as readable. I'd also argue that saving a space might be important because of line line length, but it's probably not that important. Maybe the guide could read "whichever you use, use it consistently throughout the project."

@pmjones Owner
pmjones added a note

Regarding !, all the other operators have a space between them. The only ones that don't are the increment/decrement operators; they actually change the value of the variable involved, so their behavior seems different enough to warrant a modified style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ echo "Second case";
+ } else {
+ echo "Default case";
+ }
+
+Always use braces to enclose the body of the statements. This standardizes
+how they look and reduces the likelihood of introducing errors as new lines
+get added to the body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+Do not perform variable assignment within `if` or `elseif` expressions. This
+reduces the difficulty of determining if the intent was to assign or to check
+equivalence. For example, this ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ if ($value = foo()) {
+ echo "True";
+ }
+
+... should be replaced with this, to clarify the intent:
+
+ <?php
+ $value = foo();
+ if ($value) {
+ echo "True";
+ }
+
+
+`switch`, `case`
+----------------
+
+A switch statement looks like the following. Note the placement of
+parentheses, spaces, and braces; the indent levels for `case` and `break`
+statements; and the presence of a `// no break` comment when a break is
+intentionally omitted.
+
+ <?php
+ switch ($expression) {
+
@drak
drak added a note

Are the extra line breaks here intentional?

@pmjones Owner
pmjones added a note

Good point: yes, they're "intentional" but they're not part of the requirement. Extra whitespace makes for easier reading sometimes. I'll remove them and see how it looks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ case 1:
+ echo "First case";
+ break;
+
+ case 2:
+ echo "Second case";
+ // no break
+
+ default:
+ echo "Default case";
+ break;
+
+ }
+
+Do not perform variable assignment within `switch` expressions. This reduces
+the difficulty of determining if the intent was to assign or to check
+equivalence. For example, this ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ switch ($value = foo()) {
+ // ...
+ }
+
+... should be replaced with this, to clarify the intent:
+
+ $value = foo();
+ switch ($value) {
+ // ...
+ }
+
+
+`while`, `do while`
+-------------------
+
+A `while` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ while ($expression) {
+ echo "Expression is true";
+ }
+
+Similarly, a `do while` statement looks like the following. Note the placement
+of parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ do {
+ echo "Expression is true";
+ } while ($expression);
+
+Always use braces to enclose the body of the statement. This standardizes how
+it looks and reduces the likelihood of introducing errors as new lines get
+added to the body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+It is acceptable to perform assignment within `while` expressions.
+
+
+`for`
+-----
+
+A `for` statement looks like the following. Note the placement of parentheses,
+spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ for ($i = 0; $i < 10; $i++) {
+ echo $i;
+ }
+
+It is acceptable to perform assignment within `for` expressions.
+
+
+`foreach`
+---------
+
+A `foreach` statement looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ foreach ($iterable as $key => $value) {
+ echo $key;
+ }
+
+
+`try`, `catch`
+--------------
+
+A `try catch` block looks like the following. Note the placement of
+parentheses, spaces, and braces.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ try {
+ // try body
+ } catch (FirstExceptionType $e) {
+ // catch body
+ } catch (OtherExceptionType $e) {
+ // catch body
+ }
+
+Always use braces to enclose the body of the statements. This standardizes
+how they look and reduces the likelihood of introducing errors as new lines
+get added to the body.
+
+Interweaving Non-PHP Output
+---------------------------
+
+Interweaving PHP and non-PHP using braces is discouraged:
+
+ <?php if ($is_true) { ?>
+ direct output
+ <?php } ?>
+
+Instead, use the alternative syntax for control structures:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php if ($is_true): ?>
+ direct output
+ <?php endif; ?>
+
+<http://php.net/manual/en/control-structures.alternative-syntax.php>
View
74 proposed/psr-1-coding-style-guide/0950-operators-and-expressions.md
@@ -0,0 +1,74 @@
+Operators and Expressions
+=========================
+
+Operators
+---------
+
+Operators should have one space before and after. Opening parentheses have no
+space after, and closing parentheses have no space before.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ $a = ($b + $c) * ($d / ($e - $f));
+ $foo = $bar . $baz;
+ $zim = $gir && $irk;
+
+The `!` operator should have a space between it and the expression it is
+negating.

:+1:

Increases readability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ if (! $object instanceof $class) {
+ // ...
+ }
+
+Increment/decrement operators should have no space separation:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ $i--;
+ ++$k;
+
+Casts should have a space between the type and the variable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ $foo = (bool) $bar;
+
+
+Expressions
+-----------
+
+Expressions for `if`, `switch`, etc. statements should fit on one line. If the
+expression cannot fit on one line, extract the expression into an explaining
+variable and use that variable as the expression. For example, the following
+long expression ...

:+1:

Forget my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ if (($expression1 && $expression2 && veryLongFunctionName())
+ || $expression3 || $expression4) {
+ // perform some action
+ }
+
+... should be rewritten as:
+
+ <?php
+ $set1 = $expression1 && $expression2 && veryLongFunctionName();
+ if ($set1 || $expression3 || $expression4) {
+ // perform some action
+ }
+
+If the set of expressions still cannot fit on one line, or if it would improve
+readability, split the expression onto several subsequent lines at the `&&`
+and `||` operators. Operators should align with the equals sign so that the
+expressions themselves are also aligned.

:-1:

Alignment, see my comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+
+ <?php
+ $set1 = $expression1
+ && $expression2