Skip to content
This repository

PSR-1, a standard coding convention for PHP #14

Closed
wants to merge 3 commits into from
Klaus Silveira

Each project can have it's own coding convention. For example: Symfony, Zend and Yii might have different naming conventions, as well other specific considerations (such as one class per file, line lenght, etc.). However, some rules are so generic that should be considered a standard. PSR-1 aims to be a set of generic guidelines for code formatting that can be extended by PHP projects.

Right now we have various conventions, being the Zend Framework convention the most widely used. However, such conventions are very tied to the project itself and can become a hassle to port to other projects.

With PSR-1, we can have a cohesive standard that does not take into account personal preferences or project-specific considerations. This is why it's so important that you guys contribute to my initial commit. This HAS to be a community effort and discussed a lot.

proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separe words with underscores.
1

s/separe/separate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
proposed/PSR-1.md
((3 lines not shown))
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separe words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
  18
+* When there are no parameters for the constructor method, ommit the parenthesis.
1

s/ommit/omit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Sebastian Krebs KingCrunch commented on the diff February 24, 2012
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
3

With 5.4 <?= ?> is always enabled. I think this classifies it to be allowed to.

Actually, as I know, on PHP 5.4 <?= ?> won't be considered as a short tag, but <? ?> remains

5.4 will have <?= ?> always enabled, regardless of the short_open_tag directive. I agree with KingCrunch on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Sebastian Krebs KingCrunch commented on the diff February 24, 2012
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
11

Why "no underscores"? PHP itself uses two underscores to mark "magic methods" and there is also to habit from the old PHP4 days, that private and protected were marked with a leading underscore.

This is a standard in many object-oriented languages, including C# and Java. PHP has a lot of old habits, including a complete mess when it comes to naming of native functions (some are abbreviated, others have underscore). However, native PHP classes (PDO, DateTime) have camel case has the default naming convention.

Yes, but at least Java has overloading (C# I don't know). I sometimes mark "internal functions" with underscores, that would conflicts with public ones. Of course I could rename them, but on the other hand forbidding underscores just feels little bit unnecessary too strict.

I think we should leave the underscores only to the magic methods... we don't need underscores to say that the properties are private or protected.

Type and visibility should never relate to the naming convention of variables or functions. Hungarian notation habit should be avoided.

Remember that this coding convention does not cover native functions or methods. It should cover just PHP code, not PHP itself. I believe everyone agrees that PHP itself has no naming convention whatsoever.

Sorry, maybe I said it little bit misleading. I don't use underscores to mark private or protected neither. However, I revert my objection (at this point ;)), because I realized, that I use underscores that rarely, that I can live without them.

Another point: Whats about functions? The builtin functions are mostly (? all?) underscore_separated, the methods camelCased. Should PSR-1 take this into account?

Edit: Started this comment, before I've seen yours. Sidenote: You should mention hungarian notation as a separate point :X

I think that lower camel case is good to them too.

Functions should also be camel case, in order to keep the codebase cohesive. Otherwise, people would be thinking that there's some sort of separation between functions and methods. They should use the same naming convention to avoid this idea.

Sotaro KARASAWA
sotarok added a note February 24, 2012

I have discussion about under_score or camelCase for variable names. I posted to google groups https://groups.google.com/group/php-standards/browse_thread/thread/c0583e59ba5b8052/c2d037564e405b71?hl=ja&#c2d037564e405b71

nanobe
nanobe added a note March 05, 2012

I'm confused about what we're trying to achieve here. It sounds like we're trying to standardize some basic naming conventions so that functions and classes from other projects don't feel foreign when imported into another project. But, if we standardize function and variable names to use camelCase instead of underscores, won't that make PHP's own standard library feel foreign? I don't see how we can possibly standardize on camelCase functions names without undermining the very purpose of this standard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
8

Feels slightly too strict and I don't see a benefit: If someone puts spaces there, it looks ugly, but it doesn't hurt the readability.

Following your line of thought, other rules can be considered too strict, such as indentation, wrapping space around operators, single space after keyword, etc. This rule has the same objective as the others: consistent coding style.

Yes, but I thought about it and for every point you mentioned I've found an argument:

  • Indentation: Grouping of logical coherent code blocks
  • Wrapping space around operators: Avoids "boolean-snakes"
  • single space after keyword: Syntax error otherwise :D

Damn, Github does not allow me to show a lot of spaces. Gist will help me: https://gist.github.com/1903154

if (      $var == 'crazy'        &&                             $foo != 'bar'                               )

works fine :)

However: Oh ... I thought its only about "no whitespace" against "one whitespace". But it's not completely clear to me: whats about

$array = array(
  'slightly long string',
  'Heeeelllooo (here aroud 40 characters more) world',
);

(I feel quite fussy right now ...)

This is a string. I'm only talking about parenthesis in control structures and function calls. Maybe i need to make this a little more clear.

You probably mean "array". However (thats not the point): There are cases, where if-expression may grow (If I can refactor it, to reduce it, is not the question here ;)). Isn't "either no whitespace, or a single new line" an option?

Consilience Media
consilience added a note May 16, 2012

With more examples of what we are trying to move towards, and what we are trying to avoid, it will be easier to put the right wording together to describe it. The description of the rules or conventions should be simple and clear enough to understand, but not to leave it open to ambiguous interpretations. So try starting from the sample code and working back.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Luís Otávio Cobucci Oblonczyk

I think that those things can be added:

  • Add a single space after each comma delimiter;
  • Declare visibility explicitly for class methods, and properties (even on public class members)
proposed/PSR-1.md
((1 lines not shown))
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separe words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
8

Never understand this rule: Whats the benefit? Also I find it ugly (Yes, it's an opinion, not an argument)

Personally, i also don't like it KingCrunh. However, this is a standard in many languages, including C, C++, Java, C# and others. I ended up giving up my personal preference and adopting the standard. Most languages use a style based on K&R.

Time for a change? :)

I prefer to leave personal preferences out of this. It's a solid standard not only on PHP, but other languages as well.

Christoph
xrstf added a note February 25, 2012

I think this will cause problems when using PHP as a template language. In this case you would have to write

<div>
<?php if (foo)
{
  ?>
  hello world!
  <?php
}
?>
</div>

which I think looks ridiculous. Having the braces in the same line makes it much more readable

<div>
<?php if (foo) { ?>
  hello world!
<?php } ?>
</div>

Plus, this syncs up with the additional syntax PHP provides:

<div>
<?php if (foo): ?>
  hello world!
<?php endif ?>
</div>

Read the rule again: only classes, methods and functions should have braces on a new line. The rule below discredits your comment: Conditional statements should have braces on the same line, with a single space before the brace.

But the second point xrstf mentioned seems valid: Using one rule instead of two different depending of the "kind of brace" feels more consistent.

Christoph
xrstf added a note February 25, 2012

Oh, you're right. Withdrawn. :-) But doesn't this defeat the other places in this PSR where it says "have one rule for everything", like indentation and line breaks?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Luís Otávio Cobucci Oblonczyk

The expressions used on Symfony2 code are something like that:
if (true == $value)

I think that this one is clearer:
if ($vaue == true)

Don't we should write a rule for it?

Klaus Silveira

lcobucci, i agree with your visibility statement. var should not be allowed since it's a legacy thing. Do you guys agree with such statement? I also agree with the comma.

As for the if consideration, i find this to be very project-centric as well too personal.

Sebastian Krebs KingCrunch commented on the diff February 24, 2012
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
3

Just something I thouht about myself: Whats about

  • No variable/parameter/property/...-names (in short: identifiers) longer than 30 (?) characters.
  • Line endings \n. I just ran into issues while I grepd over source, that contains both \n and \r\n. Thats just scary...
  • Line length: soft limit 120, hard limit 150

?

I tried to choose fair numbers, that should reflect, that exceeding is not only ugly, but may lead to serious comprehesion (? right word?) problems. In fact they are just placeholders.

Name lenght is very project-centric. We should not enforce this.

Line lenght is something i despise. The convention should not enforce this rule. It's often a rule of thumb in software development that can show you that a method is doing much more than it should do. Even if you do consider this a rule, this is very project-centric.

As for line endings, i agree with \n being the default.

"showing, that a method is doing much more, than it should do"? Do you mix it up with "number of lines in a method"?

However, my point was to set a limit, that is higher, than every possible (reasonable) convention. Maybe my values were a little bit to optimistic: 40 characters for identifiers, 150/180 characters max line length? The idea is, that every project specific convention can tighten this rules without violate PSR-1. Allowing lines longer than 180 (?) characters seems as illogical as mixed line-endings and even more illogical than breaking the "where to put the braces/paranthesis at"-rules.

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

The PSR-1 idea is to be as generic as possible, focusing on code convention and not project convention. Note that i didn't add a single rule about comments or documentation. Such rules are project-centric and should not be covered by the PSR-1. PEAR has it's own comments/documentation structure, as well Zend, as well Symfony, as well Yii, as well Drupal, etc. For example, naming lenght, line lenght and other "limits" are very project-centric.

I want PSR-1 to be extended by projects. For example, Symfony has a lot of project-centric considerations, and so does Zend. Both Symfony and Zend can implement PSR-1 and add specific rules. They should not, however, override the rules mentioned in the PSR-1.

Jordi Boggiano

I think we need a namespaced code sample too, with which I would add the following rule:

  • One use statement per line, no multiple declarations. (that prevents noise in diffs)
Klaus Silveira

It prevents noise in diffs and also provides better readability. I agree on this one. What do you guys think?

Fabien Potencier
Owner

This should probably be discussed on the mailing-list first.

Sebastian Krebs

What do you mean by "no multiple declarations" in this context? One namespace per file?

André R.

Great pull, I don't necessarily agree that no spaces in start and end of parenthesis and omitting empty parenthesis makes the code more readable, but nevertheless an standard on this would help us all.

@patrickallaert Did quite some work on our coding standard last year for namespaces and PSR-0, I'm not saying you should adopt it (our CS is to strict for most projects) but there is quite a lot of effort and examples you might find useful to copy and adapt: https://github.com/ezsystems/ezp-next/wiki/codingstandards

proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
10

Why? Using tabs has more advantages than using spaces.

Christoph
xrstf added a note February 25, 2012

Correct. Using tabs allows the reader to adjust the indentation as he or she likes. Plus, they use less bytes (the lamest argument ever, I know ;)). I think the main argument against tabs comes from people using tabs for alignment, which of course screws up your code when someone has a different tab width. Alignment (if any) should be done with spaces, indentation should be done with tabs.

// ~ = tab
// ° = space

if (foo)
{
~if (bar)
~{
~~// the simple case: two tabs to indent and some spaces to align the definitions
~~$x°°°= 1;
~~$foo°= 2;
~~// above works perfectly with *ALL* tab widths

~~// again: tabs to indent. Since the position of '3' and '5' depend on
~~// how long the variable is, spaces must be used to *align* the
~~// literals.
~~$longLiteral = 1 + 2 +
~~°°°°°°°°°°°°°°°3 + 4 +
~~°°°°°°°°°°°°°°°5;

~~// alternatively, you can of course just go with the 'when breaking
~~// up a line into multiple lines, just indent them' rule, which would
~~// look like this:
~~$longLiteral = 1 + 2 +
~~~3 + 4 +
~~~5;
~}
}

So when used correctly, I don't see any reasons against using tabs.

I also agree with the tabs argument. However, every single convention i have ever seen for many different languages and many different projects enforce spaces instead of tabs. Why should we be any different? Also, not using spaces would break compatibility with Zend, Symfony and PEAR.

Tabs are only useful in (office-)documents, where the character width is not equal. For code set your IDE to use a monowidth-font. When you set your IDE to use spaces as tabs, there is even no difference while coding (note, that most IDEs support [shift]-[tab] for a kind of "tab-backspace"). Additional mixing both in one file is horrible. Have a look at my comment above about "\r\n versus \n".

Technically, what @xrstf proposes makes the most sense. However there are other things to consider when developing coding standards for a project (and believe me, I have done this a few times now).

If technically it makes sense to use tabs for indent and spaces to align, this is by far much more difficult to:
1. support across different editors/IDE (they are not all good!)
2. make people stick to this somewhat more complex scheme
3. verify with style checking software and/or VCS hooks.

Basically, grepping for the TAB character is the most effective way to ensure consistency. It should simply never appear in files if CS specifies spaces as indentation scheme.

We should also try to not reinvent too much thing here and use what is really popular and consistent. Using spaces is by far the most common indenting scheme in the PHP ecosystem.

I think that the rule should be something like "Project MUST NOT mix tabs and spaces for indetation". It would be compatible with almost all projects, I think.

And if you use PHPCodeSniffer to check your CS then there is no difference between using tabs or spaces. PHPCodeSniffer supports both.

Deleted user
Unknown added a note February 26, 2012

The content you are editing has changed. Reload the page and try again.

PSR-1, a standard coding convention for PHP by klaussilveira · Pull Request #14 · php-fig/fig-standards · GitHub
basket jordans http://amicalenc.com/lunettes/basket-jordans.html

Sending Request…

Attach images by dragging & dropping or selecting them. Octocat-spinner-32 Uploading your images… Unfortunately, we don't support that file type. Try again with a PNG, GIF, or JPG. Yowza, that's a big file. Try again with an image file smaller than 10MB. This browser doesn't support image attachments. We recommend updating to the latest Internet Explorer, Google Chrome, or Firefox. Something went really wrong, and we can't process that image. Try again.

AmyStephen
AmyStephen added a note March 10, 2012

@patrickallaert "Using spaces is by far the most common indenting scheme in the PHP ecosystem."

I'd be careful with such claims unless there is some type of survey that can be referred.

I tend to agree with @kukulich that the rule requiring consistency (meaning, use tabs or use 4 spaces, but do not mix the two) seems appropriate.

I think rules this specific run the risk of alienating involvement rather than building common standards.

@patrickallaert "Using spaces is by far the most common indenting scheme in the PHP ecosystem."

just because it (maybe?) used to be this way (and partly due to legacy problems maybe still is), doesn't make it right.
the headline of the documents states "...for code formatting in modern PHP projects"
So where does modern start? now? 10 years ago? Z1-Date-of-birth?
Logically the advantages of tabs fully outweigh the ones of spaces (nowadays, with 21st century coding equipment). That has been established throughout the pro/con discussions about it (sources have been named here already - like http://c2.com/cgi/wiki?TabsVersusSpaces).
So for modern projects it is the consequential and right thing do to: tabs as code indentation (1 tab per level - "meaningfulness"), spaces for alignment (if necessary).
Yes, one might need to start using a real editor/IDE instead of a plain-text-editor if that helps to keep the standards. But that should have been the case anyway - for code completion, parse-error detection etc.

As for the output on github and other frontends: Just as markdown is automatically replacing those indentation tabs (for code lines for example) sites like github/wikis can/could also transform and display the indentation according to what fits best. but this is the presentation layer of the programm or website and does not relate to the code itself (similar to code highlighting and coloring).

Loïc Chardonnet
gnugat added a note March 11, 2012

In your opinion, how many projects will do the effort to comply to this rule, when they're using spaces in their master/dev/fix/feature branches, and while their PR are using spaces?
This PSR shouldn't force any change in existing projects, just state the current trend, and leave the debate for their own coding style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should ommit the closing tag "?>" in order to avoid accidental injection of escape characters
1

"[...] accidental injection of escape characters"
s/escape/extra/ ?

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

Not specified the nomenclature of class names. Use CamelCase with the first letter in upper case? Or at least points to PSR-0.

Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
((2 lines not shown))
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
4
Andreas Möller
localheinz added a note March 04, 2012

Concerning conditional statements, I believe it's good practice to enforce Yoda conditions.

Sebastian Krebs
KingCrunch added a note March 04, 2012

Why? The only reason for Yoda-conditions is to make inattentive developers life easier. When they want to use it, fine, but I'm against to include it in a standard.

Andreas Möller
localheinz added a note March 04, 2012

Well, you don't have to.

@KingCrunch : With you I agree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
((3 lines not shown))
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
  18
+* When there are no parameters for the constructor method, omit the parenthesis.
10
Andreas Möller
localheinz added a note March 04, 2012

This might be a personal preference, but please, don't.

Yoan Blanc
greut added a note March 04, 2012

@localheinz :+1: don't.

Sebastian Krebs
KingCrunch added a note March 04, 2012

+1 omitting the parenthesis. However, I would not put it in the standard

Andreas Möller
localheinz added a note March 04, 2012

@KingCrunch What are your arguments?

Sebastian Krebs
KingCrunch added a note March 04, 2012

ehm ... Because they are not required, so why keeping them?

$x = new A;
// against
$x = new A();
Andreas Möller
localheinz added a note March 04, 2012

:-1:

Sebastian Krebs
KingCrunch added a note March 04, 2012

@localheinz What are your arguments? ;)

Andreas Möller
localheinz added a note March 05, 2012

Consistency and readability.

:-1:

I don't see the point to introduce inconsistencies by omitting the parenthesis only when there aren't parameters. Why exception ?

Including the fact that other OOP languages like Java, C++ & C# don't omit parenthesis (for calling constructor), it could be very confusing.

IMO, I think it's more readable when I take into account the magic __invoke() and dynamic class name.

$obj = new $className();
$obj = new $className; // the same as above
$a = $obj(); // magic invoke
$a = $obj; // copy

Just my 2 cents...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
((5 lines not shown))
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
  18
+* When there are no parameters for the constructor method, omit the parenthesis.
  19
+* Wrap operators with a single space (==, !=, &&).
  20
+* A string that does not contain variable substitution should use single quotes.
11
Andreas Möller
localheinz added a note March 04, 2012

Rather than using variable substitutions in the first place, concatenation should be enforced.

Sebastian Krebs
KingCrunch added a note March 04, 2012

Don't think so: Makes things more unreadable.

Andreas Möller
localheinz added a note March 04, 2012

@KingCrunch Concatenation? Variable substitution?

Sebastian Krebs
KingCrunch added a note March 04, 2012

Concatenation.

Andreas Möller
localheinz added a note March 04, 2012

@KingCrunch You must be kidding.

Sebastian Krebs
KingCrunch added a note March 04, 2012

Nope. Variable substition in conjunction with a decent IDE is obiously more readable.

Andreas Möller
localheinz added a note March 04, 2012

Maybe it is for you.

Sebastian Krebs
KingCrunch added a note March 04, 2012

I can imagine I'm not the only one.

$number = 13;
$animal = 'monkey';
$location = array('number' => 9, 'type' => 'tree');

"There are $number {$animal}s on {$location['number']} {$location['type']}s\n";
'There are ' . $number . ' ' . $animal . 's on ' . $location['number'] . ' ' . $location['type'] . 's' . PHP_EOL;

Thus at least enforcing concatenation is a quite bad idea.

Andreas Möller
localheinz added a note March 05, 2012

@KingCrunch

The problem is, though, that you can't use a decent IDE (e.g., PhpStorm, which highlights variable substitution) in all circumstances. Thus, I agree with not being to strict with enforcing concatenation vs. variable substitution.

On a separate note, one has to ask what's the point in coming up with a standard that's just a redundant backup of existing standards, e.g. PEAR.

Jaroslav Hanslík
kukulich added a note March 05, 2012

@KingCrunch Why not use sprintf in your example?

Sebastian Krebs
KingCrunch added a note March 05, 2012

@kukulich Yes, also a solution

"There are $number {$animal}s on {$location['number']} {$location['type']}s\n";
sprintf(
    'There are %d %ss on %d %ss' . PHP_EOL,
    $number,
    $animal,
    $location['number'],
    $location['type']
);

But the main question remains: Is it useful to enforce concatenation just to avoid double quotes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
((1 lines not shown))
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
2
Andreas Möller
localheinz added a note March 04, 2012

Array Initializers

I'd like to see some rules for method and function calls, especially regarding the number of operators - this is closely related to initializing arrays:

$array = array(
    'foo',
    'bar',
    'baz',
);

I believe it makes sense to add a comma behind the last assignment in an array, as it makes it easier to shift assignments up and down and for diffs only the line with an actual change is affected.

Function/Method Calls

Concerning function and/or method calls, I've come to the following practice:

  • if for a specific call the method takes only one argument, don't wrap
$id = $this->getRequest()->getParam('id');
  • if for a specific call the method takes more than one argument, wrap
$id = $this->getRequest()->getParam(
    'id', 
    'foo'
);

Wrapping Chained Method Calls

This leads me to another topic, wrapping when using chained method calls. Personal preference, maybe, but has a reason.

  • when chaining, always wrap bevor the first method call and put the semicolon on a new line
$response
    ->setHttpResponseCode(500)
    ->setBody('Something failed')
;
  • wrap where it makes sense, as on each level, the same object is returned (compare with above)
$this->getResponse()
    ->setHttpResponseCode(500)
    ->setBody('Something failed')
;
Ludovic Fleury
ludofleury added a note March 08, 2012
$id = $this->getRequest()
    ->getParam('id', 'foo');

I know it's not a fluent interface, yet it could solve the "weird" (imho) wrap problem combined with the 75 chars line break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
((7 lines not shown))
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
  18
+* When there are no parameters for the constructor method, omit the parenthesis.
  19
+* Wrap operators with a single space (==, !=, &&).
  20
+* A string that does not contain variable substitution should use single quotes.
  21
+* A string that contains variable substitution should use double quotes. If the variable to be substituted is an array index, braces should be used. Never concatenate for this.
  22
+* Don't concatenate string and function calls.
5
Andreas Möller
localheinz added a note March 04, 2012

Also, maybe add a rule for string concatenation, e.g.

$string = 'Foo'
    . 'Bar'
    . 'Baz'
;

Probably looks a bit odd at first, but what are the alternatives? Align the dot with the = sign? This just wastes time.

Ludovic Fleury
ludofleury added a note March 08, 2012

Better readability, but seems a bit overkill.

AmyStephen
AmyStephen added a note March 10, 2012

phpStorm has a code formatting option that is quite handy.

It reformats a multi-line concatenated string as thus:

$string = $multiple
. $lines
. $indented
. $with
. $tabs;

I use this feature because it guarantees consistency.

Somehow, common standards have to be balanced against that type of time-saver. Ability to define your IDE to implement the standard will bring the best compliance. Maybe working with folks like phpStorm and other IDE providers that might be possible? Being able to select a PSR-1 conformance option and have the rules enforced would be ideal.

Jose Diaz-Gonzalez
josegonzalez added a note May 16, 2012

Thats extremely unreadable.

Rob Loach
RobLoach added a note June 04, 2012

Since string concatenation takes an operator (.), it should adopt the same formatting as regular operators.

$myvalue = 4 + 7 + 3;
$mystring = 'Hello' . ' ' . 'World!';

As for multi-line concatenation, your guess is as good as mine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Andreas Möller localheinz commented on the diff March 04, 2012
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
1
Andreas Möller
localheinz added a note March 04, 2012

Should there be a rule to enforce an empty line at the end of the file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Jose Diaz-Gonzalez josegonzalez commented on the diff March 08, 2012
proposed/PSR-1.md
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
16

Why this? All useful text editors can specify the number of spaces a tab equals. Everyone has their own preference - we use 2 spaces at work, and 4 in a particular codebase - and tabs allow you to visually specify which you prefer.

/holywar

Andreas Möller
localheinz added a note March 08, 2012

In that case, let your IDE specify what the indentation should be. If you want to use 3 spaces, tell the IDE/Text Editor that 1 tab == 3 spaces. Done.

Andreas Möller
localheinz added a note March 08, 2012
Andreas Möller
localheinz added a note March 09, 2012

Found another article which deals with indentation in different frameworks: http://www.livelywebdesign.com/blog/2011/05/tabs-versus-spaces/

Problem comes when you have your editor to do tabs as spaces with your personal preference - be it 4 as in PEAR or 2 as in Symfony - and some other developer has it setup the other way. Then you either have to have an editor that will autodetect tab indention on a file-basis, or you'll have some funny looking commits. Tabs is the sane way to go about doing this.

As far as some editors not allowing you to setup what a tab looks like, find a better editor. Every major IDE/editor I've used has had this feature, so I don't think it is a valid excuse for not using tabs instead of spaces.

http://c2.com/cgi/wiki?TabsVersusSpaces

I would very much like to see where, in the context of indentation in PHP, how using tabs vs spaces can break something. I can understand that you might be writing Python/Ruby code where they uses spaces - 4 for Python and 2 for ruby - as indentation by convention, but this is PHP. Using spaces means I can't set my editor to use the monospaced number of spaces I want to represent an indentation-level as.

Deleted user
Unknown added a note March 09, 2012

The content you are editing has changed. Reload the page and try again.

The actual mid-cap catalog trails firms with a market price that may be on average one-fifth involving blue-chips or perhaps large firms. [url=http://www.442ndrct.com/support.php?p=michael-kors-outlet-online-store]michael kors outlet online store[/url]
, cheap oakley camo sunglasses
Beckham drilled his or her son in Springfield Hillcrest Large in addition to used Green-Beckham and his youthful buddy, Darnell, who signed a letter involving intent to visit Missouri with Feb .. [url=http://www.adonim.de/tragen.php?p=louis-vuitton-artsy-online-shop]louis vuitton artsy online shop[/url]
The item drawn me into a world i always are unfamiliar and raised empathy for the shed people whom - somewhat : has anything, during a couple of weeks connected with the living. [url=http://www.abolgokh.com/support.php?p=cheap-oakleys]cheap oakleys[/url]
"Instinctively, I think were going nicely nevertheless construction wants several operate.In .
scarpe louis vuitton http://danielecerioni.com/supporto.php?p=scarpe-louis-vuitton

Sending Request…

Attach images by dragging & dropping or selecting them. Octocat-spinner-32 Uploading your images… Unfortunately, we don't support that file type. Try again with a PNG, GIF, or JPG. Yowza, that's a big file. Try again with an image file smaller than 10MB. This browser doesn't support image attachments. We recommend updating to the latest Internet Explorer, Google Chrome, or Firefox. Something went really wrong, and we can't process that image. Try again.

Upgrade to tabs. Sounds like evolution to me.

Sebastian Krebs
KingCrunch added a note March 09, 2012

Even if you try to enforce tabs, it will end up in a mix of both tabs and spaces for indentation. Then you can suggest a mix of \r\n/\n for line endings too, because grep will become a mess anyway. No reason to annoy windows users :)

As a sidenote: Symfony uses 2 spaces, but PEAR 4? Push "tab" twice, whats the problem? As long as there is no convention, that wants to see 7 spaces ... ;)

Jaroslav Hanslík
kukulich added a note March 09, 2012

There's no problem with tabs. I use tabs for all of my projects and we never end up in a mix of both spaces and tabs.

When I say "use tabs", I mean "use hard tabs". Not "pretend these four spaces are a tab and have your editor detect that".

Use tabs, and have your editor space out a tab as if it were 4 space characters. Or 2. Or 7. But then it's just something your editor can control in the presentation layer, not something you have to dick with in a pre/post-commit hook.

jose is right. every sane developer/project should use (hard) tabs (one tab per level) as indentation. there are numerous reasons NOT to use spaces for this - and they are simply not meant to indent code in the 21st century. that some projects still stick to spaces is mainly a legacy problem. Such a drastic switch is not applied easily.

Loïc Chardonnet
gnugat added a note March 10, 2012

Gentlemen, such a project oriented rule should be defined in a project coding style, not in this standard.

@gnugat Then what is the purpose of this standard? It appears to me that most - all? - of these are items which should either be standardized across the language - such as what PEP8 does for python - or just be on a project level. If the latter, why bother?

Loïc Chardonnet
gnugat added a note March 11, 2012

I was actually referring to @nateabele in the PR 16 (#16 (comment)).
The other reason of his statement is that PSR should be based on what is already used nowdays (just like PSR-0 was), see #16 (comment).

I personally think most of this spec is asinine, and doesn't do much to actually help us do what is most important. His comment on having a standard Package manager is one of those things.

For the record, we use 2 spaces at work for everything except Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Rob Loach RobLoach referenced this pull request June 04, 2012
Merged

Psr 1 style guide #25

Nate Abele

Guessing we can close this now?

Paul Dragoonis
Owner

Hi @nateabele,

Can I confirm that since PSR1 is no longer a proposed standard, but an accepted one, that we can close this PR.

Thanks.

Nate Abele

Yeah, that was intended for someone capable of closing it. :-)

Paul Dragoonis
Owner

Yep, thanks.

Paul Dragoonis dragoonis closed this September 26, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.

Showing 1 changed file with 57 additions and 0 deletions. Show diff stats Hide diff stats

  1. 57  proposed/PSR-1.md
57  proposed/PSR-1.md
Source Rendered
... ...
@@ -0,0 +1,57 @@
  1
+The following document describes the guidelines for code formatting in
  2
+modern PHP projects.
  3
+
  4
+Rules
  5
+-----
  6
+
  7
+* PHP code should be delimited by standard PHP tags. Short tags, ASP tags and script tags are not allowed.
  8
+* Files that contain only PHP code should omit the closing tag "?>" in order to avoid accidental injection of escape characters.
  9
+* Indentation consists of 4 spaces, tabs are not allowed.
  10
+* Don't put spaces after opening parenthesis and before closing parenthesis.
  11
+* After language keywords (if, else, while, switch, etc.) add a single space before the opening parenthesis.
  12
+* Don't add trailing spaces after braces, parenthesis or line endings.
  13
+* Native PHP types should be lowercase (false, null, true, array, etc.).
  14
+* Use camelCase for variable, function and method names. Don't use underscores.
  15
+* Use uppercase for constants, separate words with underscores.
  16
+* Class, method and function declarations should have braces on a new line.
  17
+* Conditional statements should have braces on the same line, with a single space before the brace.
  18
+* When there are no parameters for the constructor method, omit the parenthesis.
  19
+* Wrap operators with a single space (==, !=, &&).
  20
+* A string that does not contain variable substitution should use single quotes.
  21
+* A string that contains variable substitution should use double quotes. If the variable to be substituted is an array index, braces should be used. Never concatenate for this.
  22
+* Don't concatenate string and function calls.
  23
+* Inside switch statements, the break keyword is aligned with the case keyword indentation.
  24
+
  25
+Example implementation
  26
+----------------------
  27
+
  28
+    <?php
  29
+
  30
+    class Example
  31
+    {
  32
+        const CLASS_CONSTANT = 1;
  33
+
  34
+        private $var;
  35
+
  36
+        public function executeTest($foo, $bar, $item)
  37
+        {
  38
+            if ($foo == 'crazy') {
  39
+                $foobar = "Hey! I'm $foo and this is my {$item['weapon']}";
  40
+            }
  41
+            
  42
+            switch ($bar) {
  43
+                case 'people':
  44
+                    return;
  45
+                break;
  46
+
  47
+                default:
  48
+                    $bar = true;
  49
+                break;
  50
+            }
  51
+
  52
+            return $foobar;
  53
+        }
  54
+    }
  55
+
  56
+    $obj = new Example;
  57
+    $obj->executeTest('crazy', 'nothing', array('weapon' => 'BFG'));
Commit_comment_tip

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.