PSR-Huh?

PSR-Huh?

Tutorial Details
  • Topic: PHP Standards
  • Difficulty: N/A

If you’re an avid PHP developer, it’s quite likely that you’ve come across the abbreviation, PSR, which stands for “PHP Standards Recommendation.” At the time of this writing, there are four of them: PSR-0 to PSR-3. Let’s take a look at what these are, and why you should care (and participate).


A Brief History

PHP has never truly had a uniform standard for writing code. Those who maintain various codebases commit time to writing their own naming conventions and coding style guidelines. Some of these developers choose to inherit a well-documented standard, such as PEAR or Zend Framework; yet others choose to write standards completely from scratch.


The Framework Interoperability Group

Do not hesitate to open a new topic in the mailing list.

At the php|tek conference in 2009, people representing various projects discussed their options for working between projects. It surely comes as no surprise that sticking to a set of standards between codebases was the main agenda item.

Until recently, they labeled themselves as the “PHP Standards Group”, but now, they operate under the umbrella, Framework Interoperability Group (FIG). As they felt, the former didn’t accurately describe the group’s intentions. Even though the name of this group explicitly refers to frameworks, developers representing all sorts of projects have been accepted as voting members.

The FIG intends to host a cross-section of the PHP ecosystem, not exclusively framework developers. For example, the Symfony, Lithium and CakePHP frameworks each have a representative as a voting member, but the same goes for PyroCMS, phpDocumentor, and even Composer.

The voting members can start or participate in votes, however, anyone else (including you!) can become a PHP-FIG community member by subscribing to the PHP-FIG mailing list.

This mailing list is where discussions, votes, suggestions and feedback take place.

The Goal

The goal of the FIG is to create a dialogue between project representatives, with the aim of finding ways to work together (interoperability). At the time of this writing, that dialogue has spawned four PHP Standards Recommendations: PSR-0 to PSR-3.

Those recommendations are free and can be adopted by anyone, though no one is obligated to do so. In fact, voting members are not required to implement any of the PSRs in the projects that they represent!


PSR-0: Autoloader Standard

PSR-0 is a huge step forward for reusable code.

Remember how you used to specify many require statements to reference all of the classes you require? Thankfully, this pattern changed with PHP 5′s magic __autoload() function. PHP 5.1.2 made autoloading even better by introducing spl_autoload(), which allows you to register a chain of autoloading functions with spl_autoload_register().

No matter how good the autoloading functionality is, it does not define how to implement it with existing codebases. For example, library X might approach the directory and classname structure differently than library Y, but you might want to use both!

Writing a proper autoloader that knows where to look for all possible fully-qualified names, as well as test all file extensions (.class.php, inc.php, .php etc) will quickly become a mess. Without a standard to define how to name classes and where to place them, autoloader interoperability would still be a pipe dream.

Meet PSR-0. A standard recommendation that describes “the mandatory requirements that must be adhered to for autoloader interoperability.”

PSR-0 is a huge step forward for reusable code. If a project follows the PSR-0 standard and its components are loosely coupled, you can simply take those components, place them within a ‘vendor’ directory, and use a PSR-0 compliant autoloader to include those components. Or, even better, let Composer do that for you!

For example, this is exactly what Laravel does with two Symfony Components (Console and HttpFoundation).

The FIG has an example implementation of a PSR-0 compliant autoloader function that can be registered to spl_autoload_register(), but you are free to use any of the more flexible implementations, such as the decoupled Symfony ClassLoader or Composer’s autoloader.


PSR-1: Basic Coding Standard

PSR-1 focuses on a basic coding standard.

There was a lengthy period of low-activity in the FIG after PSR-0′s acceptance. In fact, it took a good year and a half before the PSR-1 and PSR-2 documents were approved.

PSR-1 focuses on a basic coding standard. It refrains from being too detailed, and does so by limiting itself to a set of ground rules to “ensure a high level of technical interoperability between shared PHP code”.

  • Only use the <?php and <?= tags.
  • Only use UTF-8 without BOM for PHP code.
  • Separate side-effects (generate output, access a database etc.) and declarations.
  • Enforce PSR-0.
  • Class names must be defined in StudlyCaps.
  • Class constants must be defined in upper case with underscore separators.
  • Method names must be defined in camelCase.

The ground rules focus on naming conventions and file structure. This ensures that all shared PHP code behaves and looks the same way at a high level. Imagine an application that uses numerous third-party components, and they all use different naming conventions and character encodings. That would be a mess!


PSR-2: Coding Style Guide

PSR-2′s purpose is to have a single style guide for PHP code that results in uniformly formatted shared code.

PSR-2 extends and expands PSR-1′s basic coding standards. Its purpose is to have a single style guide for PHP code that results in uniformly formatted shared code.

The coding style guide’s rules were decided upon after an extensive survey given to the FIG voting members.

The rules in PSR-2, agreed upon by the voting members, do not necessarily reflect the preferences of every PHP developer. Since the FIG’s beginning, however, the PHP-FIG has stated that their recommendations have always been for the FIG itself; others willing to adopt the recommendations is a positive outcome.

The full PSR-2 specification can be found in the fig-standards repository. Be sure to give it a read.

In an ideal world, every PHP project would adopt the recommendations found in PSR-1 and PSR-2. However, due to taste (i.e. “Naming convention x looks better than y!”, “Tabs over spaces!”) and historical segmentation between various coding styles, there have only been a sparse amount of PHP projects adopting PSR-1 and PSR-2 in its entirety.


PSR-3: Logger Interface

PSR-3 describes a shared logging interface.

PHP Standard Recommendation #3 is the most recent addition to the accepted FIG-standards. It was accepted on December 27, 2012 with an impressive vote count of 18 to 0 (8 voting members did not cast a vote).

PSR-3 describes a shared logging interface, incorporating the eight Syslog levels of The Syslog Protocol (RFC 5424): debug, info, notice, warning, error, critical, alert and emergency.

Those eight Syslog levels are defined as method names, which accept two parameters: a string with a log $message and an optional $context array with additional data that does not fit well in the former string. Implementers may then replace placeholders in $message with values from $context.

A shared interface standard, like PSR-3, results in frameworks, libraries and other applications being able to type hint on that shared interface, allowing developers to choose a preferred implementation.

In other words: if a logging component is known to adhere to PSR-3, it can simply be swapped with a different PSR-3 compliant logging component. This assures maximum interoperability between calls to logger implementations.

Monolog recently implemented PSR-3. It’s therefore known to implement the Psr\Log\LoggerInterface and its associated guidelines found in the PSR-3 document.


Criticism

The PHP-FIG is doing a great job of centralizing PHP standards.

Some people say that the PSRs go too far to define a global set of standards to define a coding style – something that is more subjective than objective. Others feel that a shared interface is too specific and not flexible. But criticism comes naturally with any standard initiative. People don’t like how identifiers are supposed to be named, which indentation is used, or how the standards are formed.

Most of the criticism and reflection takes place from the sideline, after the standards are accepted – even though the standards form in the mailing list (which is open for everyone to join in and leave feedback, comments or suggestions). Do not hesitate to open a new topic in the mailing list, if you think you have something valuable to add.

It’s also important to keep in mind that it’s not the specific combination of rules, which contribute to the benefit of the recommended standards, but rather having one consistent set of rules which are shared among various codebases.

By everyone shirking their own preferences, we have one consistent style from the outside-in, meaning I can use ANY package – not just whichever happens to be camelCase.

- Phil Sturgeon in the PHP-FIG mailing list


The Future

The FIG intends to host a cross-section of the PHP ecosystem, not only framework developers.

With a growing number of influential voting members and four accepted standards, the FIG is certainly gaining more traction in the PHP community. PSR-0 already has widespread usage, and hopefully PSR-1 and PSR-2 will follow suit to achieve more uniformity in shared PHP code.

With the shared interface defined in PSR-3, the Framework Interoperability Group took a new turn in recommending standards. They are still heading in that direction, as the contents of new shared interfaces are being discussed on the mailing list.

Currently there is an interesting discussion about the proposal of an HTTP Message Package, which holds shared interfaces for implementing an HTTP client. There are also various discussions proposing a shared Cache interface; but, as of now, it seems to be on low-activity.

No matter what the outcome of those proposals will be, the PHP-FIG is doing a great job of centralizing PHP standards. They are without a doubt influencing the PHP ecosphere in a positive manner, and hopefully their efforts will obtain a more prominent place in the PHP programming language.

Remember: currently, they still operate under the name of the Framework Interoperability Group, and have no intentions whatsoever to tell you – Joe the Programmer – how to build your applications. They merely recommend a set of standards that anyone can adopt.

Tags: phppsr
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • include

    - Space instead tabs
    - camelCase
    - Various others

    PSR is just bullshit…

    • Ardakilic

      Although the purpose is nice, but I couldn’t agree more with you.

    • Gabriel Rodrigues

      Though I agree that space instead of tabs is evil, what’s the problem with camelCase? I use it in conjunction with hungarian notation…

      • http://www.facebook.com/roosterjm2k2 Joshua McDonald

        How is spaces instead of tabs evil?

        In pretty much every editor, you can switch between them, as well as retabbing the document with a click/shortcut – and most editors have soft tabs to handle your input. Its teh most trivial difference I can imagine when it comes to any part of any coding standard – one way or the other, it has absolutely no effect on my workflow.

    • iDontEven

      doesn’t change anything, just use an IDE to replace tabs with spaces and it doesn’t change a single thing on your workflow. but i guess people that hates that must be the ones pressing space 4 times for each line so

    • http://twitter.com/WouterJNL Wouter J

      It is a nice job to just scream bad things about a job of another person, isn’t it?

      Please, if you don’t agree with the coding standards, subscribe to the mailing list. Open a topic and tell them why you don’t like it. Go and find arguments for your opinion, not just random negative words.

      That’s the nice thing of a community. If everyone explain to other ones why they don’t like it, things will change, otherwise things don’t change and you can just keep screaming…

    • http://www.facebook.com/roosterjm2k2 Joshua McDonald

      Differing opinion = bullshit to you, huh?

      Diminished brain capacity presents in such varied ways…

      If the space/tab thing catches you up, I feel bad for you. Any decent editor converts between the two without issue, and most editors allow for soft tabs, so I, along with just about any other intelligent developer, have to question why people like you have such a hard time with it….

    • http://twitter.com/philsturgeon Phil Sturgeon

      Why is something bullshit just because it does not match your personal preference? If we picked snake_case for methods (which would be going against how PHP styles its core classes) then all the developers who camelCase would be annoyed too. It can’t match everyones personal preference.

      • Da

        Is that how you guys decided to go for camelCase? Do you mean from Zend Framework classes or from PHP’s own classes?

        In my honest opinion I think you should look at what makes most sense, not what anyone else is doing.

      • Ant Cunningham

        PHP’s internal classes use camelCase (@see PDO, SPL, StdClass, etc.) Only functions use snake_case. There are probably some older extensions that may use snake_case (Mysqli maybe?)

  • Andrei Zisu

    The consistency PHP needed for a while

  • http://www.facebook.com/jake.e.wilson Jake Wilson

    PSR-2 is inconsistent:

    – Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
    – Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.
    - Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

    and spaces instead of tabs?? Really?

    • Gabriel Rodrigues

      Opening braces on the next line should be banned from web development due to the way javascript works. It’s best if we all learn to open braces on the same line and avoid javascript’s quirkiness with semicolon insertion later. I used to open them on the next line, but it took me like one day to adapt.

      As for using spaces for indenting, I’m 100% with you. WTF were they thinking?

      • jeff_way

        So, to be clear, you believe that a standard some be set for PHP, because of a quirk with how JavaScript is parsed?

      • Gabriel Rodrigues

        I think that brackets on the same line or on a new line are usually a question of preference alone.

        However, due to this quirk with javascript, the scales are tipped in favor of opening on the same line. This means web developers (regardless of language) who adopt “opening brackets on the same line” get more benefits than those who don’t.

        This means that, all else being equal, same-line-brackets should be adopted in the standard.

      • http://www.facebook.com/people/Eli-McMakin/1436543193 Eli McMakin

        Jeff, out of curiosity, what is the reasoning behind putting the braces on their own lines? Or is it just “syntactic sugar”?

      • JeremyMcPeak

        @Eli: Preference?

      • André Fischer

        Braces on their own line is also known as “Allman style”. A good explanation lives at: http://en.wikipedia.org/wiki/Indent_style#Allman_style

      • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

        Thanks god that my text editor does the indentation for me.

      • Da

        Agreed

      • iDontEven

        aren’t you the same guy that said OOP sucks? i see

      • Gabriel Rodrigues

        I never said such thing.

      • Jared Hocutt

        I think you’re missing the fact that these aren’t JavaScript standards, but rather PHP standards. I can’t imagine that they’re very worried about some quirk in JavaScript.

        While I prefer tabs over spaces in most cases, if you read through PSR-2 it gives a reason why they chose this: “Using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations. The use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment.” This seems to be a fair enough argument to me and has some valid points. In the end, most people are using an IDE or text editor that supports handling this tabs/space issue for you and it shouldn’t cause anyone much headache to change the settings.

      • http://twitter.com/montanaflynn Montana Flynn

        I’m probably not the only web developer who switches between php and javascript quite regularly. Also, I prefer on the same line.

      • Jared Hocutt

        I am in agreement with you. I use both heavily in my day to day work and prefer them on the same line, But that doesn’t mean that one language’s standards (PHP) need to be a particular way just because another language (JavaScript) that it is typically used with does it that way. My only point is that each language has it’s on set of standards and they shouldn’t necessarily be changed/influenced by the standards of another just because they are similar.

    • aldoutrera

      The use of spaces instead of tabs it’s been well known for quite a while, specially to those familiar with the PHP PEAR standards. From the PEAR site “Use an indent of 4 spaces, with no tabs. This helps to avoid problems with diffs, patches, SVN history and annotations.” So that’s why spaces are preferred.

      Most of the IDES I know, if not all, allow to translate tabs to spaces, so when you press tab, the IDE instead will place X number of spaces, so this “spaces instead of tabs??” is not a problem at all.

      • Da

        Agreed, it’s annoying to see so many people complain about something without knowing what they are talking about.

        If they use Git or other versioning software they would know this by now.

  • Grant

    coming from a java environment some of these standards are already adhered to but there are certain ones i’m not in agreement with or confused by
    - spaces instead of tabs – no thanks (prefer tabs)
    - class name brace on new line while control structure brace on same line – no thanks (prefer same line)
    - use elseif instead of else if – why?
    - the side effects one simply confused by that one

    • Sebastian Krebs

      > – use elseif instead of else if – why?

      Because you asked: elseif is a single keyword and therefore directly identifiable as such. With this in mind someone can come and ask “why should I use “‘else if’ instead? Isn’t this in fact ‘else { if ($c) {}}’? But thats not, what I want to say!”

      tl;dr: Why not?

      > – spaces instead of tabs – no thanks (prefer tabs)

      You never tried to handle source files with regular expression, did you? ;)

    • http://twitter.com/GaryJ Gary Jones

      > (prefer …)

      And that’s the point of the PSRs – to avoid personal preferences in favour of code that is interoperable.

      > – the side effects one simply confused by that one

      Basically, don’t have a file that has both a class or some other resource (interface, trait, collection of functions etc.), and code that would immediately perform some action (i.e. instantiate a class, globally call a function etc.)

  • http://twitter.com/creatifcode Nenad Petkovic

    To late for any standard recommendations for PHP. After years and years of coding without any guides or with so many guides how many coders you ca count, it is simply to late to introduce any standards.

    • Gabriel Rodrigues

      What? That’s just bullshit.
      It’s akin to saying “after years and years of violence, it is simply too late to introduce police”.
      What do you expect us to do? Drown in a sea of cowboy coders and let PHP rot in obscurity? You’d like that, wouldn’t you?

      • Da

        What gives you the idea that PHP is rotting in obscurity?

      • Gabriel Rodrigues

        Read my post again, you clearly failed to understand it.

      • Da

        Why do you avoid the question?

    • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

      How exactly do you came to the conclusion that it is too late?

    • Jared Hocutt

      Unwillingness to change can be the death of a good programmer.

    • http://twitter.com/philsturgeon Phil Sturgeon

      Nobody is trying to tell average Joe Programmer what to do. The article clearly states that, and the goals of the FIG states that pretty clearly on the website http://www.php-fig.org/

      The 20ish projects involved are making themselves more interoperable, and component developers are joining in because it makes their components more reusable and framework agnostic. What you do is totally beyond the scope of things I or anyone else in the FIG care about.

    • http://twitter.com/macodev Marco Cervellin

      It’s a natural evolution based on how programmers collaborate so much more today than in the past thanks to social interoperability. Innovation and change is mandatory in our fast paced internet world.

  • http://www.facebook.com/profile.php?id=5241456 Bryan Paronto

    Someone explain to me the hate for space instead of tabs? Every text editor I’ve seen can easy be set to use ‘soft tabs’ aka insert a of ‘space’ characters when the tab button is hit. To me this is more consistent as you files dont end up being a mix of both characters.

    • Gabriel Rodrigues

      Who says you have to mix? That’s definitely worse than space-only. Stick to tabs.
      Also, it’s easier to convert tabs to spaces (a simple find and replace) than it is to convert spaces to tabs (some strings can have spaces in them).
      In addition, the whole point of tabs is to indent! They’ll even make your code line up perfectly even if you’re not using a monospaced font (If you aren’t using a monospaced font on your IDE, though, you are a masochist and your opinion is invalid).

    • Anthony McLin

      If you use spaces, how many spaces for a single level of indentation, 2, 4, 3, 7? Everyone has their own preference for what they consider legible, and every project or company has their own styling requirements for which is right.

      However, If you use tabs, it doesn’t matter. Devs can set the tab to visually display at whatever their own preference is. 1 tab = 1 level of indentation, regardless of whether that looks like 2 spaces in my editor vs. the 5 spaces in yours.

      • http://twitter.com/junkjet Dave

        Different IDEs have different defaults too, usually either 4 or 2

      • Wilson

        But a tab’s a tab, the actual ‘width’ of the tab can be adjusted by most editors.

      • http://www.facebook.com/roosterjm2k2 Joshua McDonald

        And the same can be done in most editors with spaces as well…

      • http://www.facebook.com/roosterjm2k2 Joshua McDonald

        If 20+ year old vim can retab a file anyway i see fit without issue… soft tabs at any legth or real tabs – back and forth all day long – i dont see why anyone would use an editor that cant handle such a simple task…

      • http://twitter.com/philsturgeon Phil Sturgeon

        You nailed the problem. It looks different in various editors, or browsers. Spaces work consistently everywhere, so while tabs are ok on the left, tabs to align code never work properly. By using spaces everywhere everything is always consistent.

        And as for “how many do I use” PSR-2 clearly states that you should use 4.

      • Anthony McLin

        Looking different is OK. If I like indents to be 2 character widths, and you like them to be 8 character widths, then as long as we both represent that with 1 tab it doesn’t matter what our preference is. Our code is identical.

        However, if we use spaces, then we fight over the number of spaces it should take to represent an indent.

        If you aren’t indenting, and just aligning code, I usually use a combination of tabs and spaces. Tabs to match the indentation level, and then spaces to accommodate alignment.

  • Salman Abbas

    lol at the comments.. stick with your underscores and tabs noobies.

    • Ian

      I fail to see the issue with underscores, I think it makes the code significantly more readable. Also I use camel casing for JavaScript, which mentally just helps me when constantly switching between the two

      I don’t see what is “noobie” about underscores given it’s used by an overwhelming amount of professionals and frameworks.

    • hirun

      as far as I remember all php core functions are underscored. There are not camels there, right?

  • http://www.facebook.com/jesus.bejarano.948 Jesus Bejarano

    I just change in sublime text the option “tab_size” = 2 (space). Problem solve.

  • iDontEven

    I like PSR/PHP-FIG because it will cause a separation of the community and code base. The ones that care about code quality and all the benefits you get from adopting a universal pattern, instead of being a stubborn neckbeard that can’t see beyond the tabs and spaces, will end it up working together with better and more stable code. This way we might be able to say our main language is PHP without any shame.

    • Da

      Why do you think you are better then everyone else who is not using the PSR standards?
      Why are you ashamed to say PHP is your main language? I’m not.

  • mattsah

    Criticisms for the first three… not gonna waste my breath on the last one.

    PSR-0: This “standard,” forsakes namespacing for directory structure, essentially encouraging the creation of arbitrary namespaces because a developer wants certain types of code in one place. This can be seen in a number of framworks, including one of the ones you cited in the article where they end up stacking all exceptions in a single folder call ‘Exceptions’ or ‘Exception’.

    This usually causes additional hilarious repetition of words too like our …FileExceptionFileException.php exception. PHP namespaces are verbose enough to begin with. Imagine if it looked more like this:

    FileAccessDeniedException
    FileException
    FileNotFoundException
    FileUnexpectedTypeException
    FileUploadException

    Suddenly, we can see how nice this is from a namespacing perspective… it also means components in File wouldn’t need to alias FileException and still type ExceptionFileException to throw basic exceptions… they would simply “throw new Exception()”.

    Unfortunately, the developers decided that was a bad idea because then in accordance with PSR-0 they would have to have all those files mixed in with the rest of the File classes, and alphabetical order can be a @#$% for finding things in a stack of even 10 files.

    Only in the PHP world does a standard change your architecture/code because of how you want to organize directories.

    PSR-1 and PSR-2: The problem with these is that, put simply, coding standards have nothing to do with interoperability. It might have something to do with contributing to developer uptake and how easy it is for one to work with the code of others… but regardless of how sloppy it is, unless it’s a syntax error, it seems odd to be put forth by an “Interoperability Group.”

    • lsmith77

      @mattsah: your criticism of PSR-0 is valid, yet imho the benefits of PSR-0 outweigh this draw back. as for your argument against PSR-1/PSR-2 .. reading the comments complaining about tabs vs. spaces illustrates how important it is to standardize on coding style to help collaboration. imagine every contributor complaining to you about the use of spaces or tabs?

    • dlsniper

      I’d really want to know what you have against PSR3.
      If you really think it’s that bad, why don’t you join on the mailing list and express your opinion there?
      Just random bashing about something without bringing reasonable arguments doesn’t help anyone.

      And like you’ve said, I ain’t gonna waist my time to refute your other complaints.

      • mattsah

        So you’re OK with the bashing of PSR-0 thorugh PSR-2, but PSR-3 draws the line?

        PSR-3 is clear cut bad implementation. Sure, let’s add all our constants to a class! Now we get to do LogLogLevel::EMERGENCY as opposed to just LogLEVEL_EMERGENCY. I also find it very odd that they chose to have a separate method for each type of level on the log interface — as opposed to leaving that up to the developer and simply offering the log() method… I mean, unless someone can tell me a good reason why I want to have to implement every single one of those methods when $logger->log(LogLogLevel::EMERGENCY, $message, $context) would do just as well, BTW… if you don’t see what is so utterly absurd about that previous line right there (which could and most likely will be a real line in people’s code… then I can’t help you anymore.

        Unfortunately, now you’ve made me waste my breath.

      • dlsniper

        No, I’m not OK with bashing of those standards without any good reason. I guess people just don’t like having to follow rules that are written but it’s ok when they are imposed indirectly (happens every time when you use a framework or library, start your work on a new project or a new company).

        If people would actually bother to read why those PSRs are there, how where they created and came with useful comments instead of random bashing, I guess the world would be a better place but that’s not possible since this is PHP and everything has to be free and open and fit to each and every programmer that uses it.

        Now on your PSR-3 wasted breath bashing thingy you got going on.

        I’m very glad you did put your arguments against it here as it allows me or someone else the chance to help you understand it better, hopefully.

        When you put it this way, the things don’t look pretty indeed. It’s all f***d up to be honest. What was in their mind when they’ve made us have a class that stores constants only?!

        If you’d spend the same amount of time that it took you to do/read the posts here and make some research on the mailing list, which is public and specially created so that everyone can contribute to it, before negating it you’d be able to understand why.

        Actually there are a bunch of valid reasons for why PSR-3, which passed with 18 votes out of 25-26, looks as messed up as that.

        One is called compatibility with the existing solutions and ease of adoption process. Reading the mailing list would have revealed you that all the people involved in it decided it’s easier to adopt the new PSR if the logging levels would be defined in another class and methods are called like that.

        For the having that waste of time implementing methods that are shortcuts to the log() method well… try and think about the waste of time in having to write the whole namespace for log type constant.

        And since everyone there decided that interoperability is the main goal of the interfaces (FIG = Framework -notice- Interoperability -/notice- Group) how would it look if you’d use Monolog to do the whole $log->emergency() and then you decide to switch to log4php (not compatible yet but WIP) and that library wouldn’t have the method there.

        Having the shortcut methods present there would ensure that people who prefer readability of them over being standards compliant can replace the libraries at any time.

        Also, besides PSR-0, I don’t think anyone who’s not a library author or a open source project author should be so dramatic about things. There’s a special case for PSR-1 and PSR-2 which I’ve treated here: http://florinpatan.ro/2013/01/18/this-is-php-why-do-we-need-coding-style-standards/ and so I could paste the link to anyone who’s commenting about them.

        Why shouldn’t you be so dramatic about the rest? Simple. Do you use a PHP framework that adopted/will adopt PSR-3? Great. The framework will make you use the standard. Do you use a framework that isn’t PSR-3 compliant? Great! That framework will get you used to its standards and guess what will happen when you’ll move to a different framework with its own standards… You don’t use frameworks or at least libraries? Beautiful! It means you are reinventing the wheel most of the times (and if you try the argument of: frameworks are slow, there’s a Varnish for that and I bet I can refute most if not any other arguments against them).

        Will Cache be as messed up as PSR-3? Will Http be as well? If you think so, join the mailing list and start contributing. Come with arguments, be open to others problems and try to create a better world. By staying in the comfort of the bubble surrounding your world you won’t be able to understand why things are made as they are. Get out and contribute, expand your horizons, express your opinions and try and get valid reasons for them. It’s a big, really really really huge step from creating software on demand to creating open source software to creating standards that a whole community of hundred of thousands of people, all with their views and ideas about what’s right or wrong.

      • mattsah

        So what other logging utility uses those shorthands aside from Monolog? Just curious.

        I don’t have any particular problem with anything you stated in *theory* regarding how standards could be formed in the PHP community. I’ve written pretty clearly about this topic in the past, and perhaps you’re not familiar with me, but being the resident contrarian I called out PSR-3 before it even happened.

        From my blog (prior to PSR-3 even being a proposal as far as I’m aware):

        “I started this article talking about FIG. The point I was making there
        is that the most important role for a group like FIG at this moment is
        to begin defining interfaces and, for that matter, good interfaces.”

        The key point there being “good interfaces,” as I later (in the article) qualified my position with the following:

        “Interfaces are everything to PHP developers. If all
        that’s left to us is to come up with how precisely one should implement a
        given method, in light of the fact that the method has clear arguments
        and a clearly desired return value, we lose much of the creativity of
        the community.”

        I think you continue to miss the larger point here which is quite simple. So far the “Framework -notice- Interoperability -notice- Group” as you put it has given us the following:

        1) A standard which provides little bearing on interoperability with the exception of only one of its clauses, namely that namespaces should begin with VendorModule.

        2) Two additional standards that have absolutely nothing to do with actual interoperability.

        3) An interface which would have continued to work for everyone in the world **including monolog** if they had not bothered to implement 6 or so methods which serve almost no purpose other than forcing the developer to write them to wrap the *single* method that really does matter.

        In particular on PSR-3, people seem to forget that interfaces are not designed so that the logging class you wrote will work with any framework or other library, but so that the frameworks or libraries will work with any logging class, or for that matter a mock.

        The entire premise of FIG is backwards. We don’t write interfaces around frameworks, we write frameworks around interfaces.

        Believe me, I understand that this concept is difficult to grasp, but with enough time you (and anyone arguing for backwards compatibility in FIG) will get it.

        So, forgive me if I don’t adopt PSR-3 for my new logging class. This is not to say that my framework wouldn’t be *compatible* with PSR-3 Logging classes, afterall, if all I ever used was the log() method in my dependent code, then any PSR-3 class would work fine, all additional methods would just be ignored… the problem of course is that now I have no !@#$ing way to do that because there’s still no standardized interface that only requires an implementation of log() — which PSR-3′s interface could have just #$%^ing extended instead of writing a single god damned interface because it happened to be what Monolog did.

        YOU STILL DON’T GET IT! And neither does FIG (as a voting group), or apparently any significant majority of their community.

      • mattsah

        Correction to the above: We SHOULDN’T write interfaces around frameworks, we SHOULD write frameworks around interfaces.

        FIG just makes it clearer that we (as a community) do thing wrong; despite our best efforts to become as good at OOP as communities with native OOP languages, we have failed.

      • dlsniper

        OOP is not native to PHP 5? Quick, someone call Rasmus, the Zend guys, the core contributors and the rest of the PHP community, they’ve all got it all wrong. /sarcasm off

        You know we are in PHP 5.4 age, no? Check PHP 5.5 which will come in a few months.

        And what you say about interfaces is true but you miss one small thing.

        Those frameworks have quite a large user base and a large community of contributors around them. If they all sat together and determined what’s common / how things should look in the future, they are covering the needs to provide something usable when implemented in a non-framework environment then I guess they indeed found the best interface and then moved to adopt it / provide bridges for it.

        Thanks for mentioning you have a blog and that you’ve knew about PHP-FIG, the mailing list and PSRs and yet you did nothing to correct those horrible horrible standards they are defining there (please ignore this if you where there and added your contribution but I couldn’t find your username there nor your real name).

        And just by having this dialog here it proves that you’d rather have this kind of talks on random articles, or your blog, that go to the mailing list and talk them with the people involved and help them improve.

        IIRC someone from PHP-FIG actually explained why there was a need for having PSR-1 and PSR-2. I think it was something like this: PHP-FIG itself also needed to have a standard way to deliver the next PSRs, which are all about interfaces unlike PSR-0, in a consistent manner and since PHP-FIG is composed by many members, 26 currently, all with various projects and coding style they’ve went neutral. Do you want to use them as well? Ok, go for it. No? Ok, great, they won’t reflect the degree of interoperability in anyway.

        Now, to your really strange view about PSR-3 and how they’ve come about it as well as your view about interfaces and architecture in general.

        Since there’s only a handful of used logging libraries there they’ve studied how things work in there, how they could be improved and how they make something that makes sense.

        They didn’t designed the interface around the frameworks, they’ve designed something that happens to be along side with what many where doing for a long time now.

        Look on the other proposals, Http message and Cache. They are all about what’s on the market now and how we can make it better. Same goes for the talks about e-mail sending interface.

        The point is not to reinvent the wheel completely for every proposal if it can be adapted from existing solutions to something better and useful for everyone.

        All I can see is that you are full of rage against the PSRs is based on the fact that they are not something new, they’ve just refactored them into something better.

        You don’t like them? Make your own framework and prove how everyone else is not understanding the way things should be done. Get the user base that the projects there have then bash them as hard as you can without good reasons. You already have your framework and you hate PHP-FIG so the first steps are done ;)

        Even Monolog compatibility was broken for PSR-3 but it quickly adopted it. And afaik no library was compatible with it. So no PSR-3 was in fact a BC break for everyone ;)

        As for your view on software architecture… Now this, this made me laugh to the point of tears:
        “Interfaces are everything to PHP developers. If all
        that’s left to us is to come up with how precisely one should implement a
        given method, in light of the fact that the method has clear arguments
        and a clearly desired return value, we lose much of the creativity of
        the community.”

        Are you serious? Are you really that ignorant and serious at the same time? How can you say that having the arguments defined in a function limit your implementation?

        If interfaces are anything to a developer in PHP then can you explain please how would you design a generic interface for objects that have the same basic functionality and that can be exchanged at any time the user wants to do it but they don’t provide a clear parameter list / hinting for the methods that they contain?

        Take this example:
        LibALog::log($message = ‘Demo’, $context = ‘main’)
        LibBLog::log(LogMessage $message)
        LibCLog::log($message = ‘demo’, $priority = ‘servers are down’)

        Can you understand why not having a defined list of parameters / hinting would be a problem for a -GENERIC- interface?

        Let me explain it to you since it’s clear that you couldn’t come up with the above example on your own.

        That’s a pretty creative way of doing logging, don’t you think?

        You see the problem that I would be faced as a user if I were to decide to switch from LibA to LibB or LibC? All my code would stop working and I’d need to spend some time to fix it. And to be honest I’m not payed on number of changes done/lines of code written.

        The only way to allow you to be creative would be:
        LibZLog::log()
        but that’s so wrong I wouldn’t even consider it outside of this talk.

        And do six additional methods that are syntactic sugar really bother your when implementing a library but what you said makes perfect sense?

        PSRs are recommendations for non-frameworks people and optional even for members. It just so happens that maybe 60-70% of the active frameworks and more that a handful of users are there but I’m sure it’s a pure coincidence and those PHP-FIG people don’t have a clue about how to design software and you are right ;)

        Try not to take it so hard, your bubble seems to be full of misguided hate imho so you should try to relax a bit and read the history of something, learn from it before going head first into it. Else the hate in your bubble will only increase and that’s not healthy for you. It might also save you some breaths ;)

    • http://twitter.com/Inoryy Roman Marintsenko

      Your PSR-0 example makes sense as long as you stick to your example.
      Once you look at any real project adopting PSR-0, you see that your point doesn’t stand anymore, i.e.

      `MattFileExceptionAccessDeniedException` – looks sensible, doesn’t it?
      And actually makes much more sense than `FileAccessDeniedException` (which file? which component? whose component?)

      • mattsah

        You misunderstood what I was saying. I wasn’t talking about killing the vendor and/or project if indeed it’s a file component of a particular project and not just a file component. I was talking about the separate ‘Exception’ namespace — the examples I gave were shortened in the context of the paragraph above where I noted: “…stacking all exceptions in a single folder call ‘Exceptions’ or ‘Exception’”

        If you prefer (or need) me to give a full example, here:

        DotinkProjectFileException instead of DotinkProjectFileExceptionFileException … do you see the point now?

        AGAIN! the problem is not the preceding namespacing. I don’t disagree that the convention makes sense… what I disagree with is essentially mapping namespaces directly to directories because it pushes us into creating namespaces for the sake of wanting to organize our files.

      • dlsniper
  • http://www.facebook.com/people/Eli-McMakin/1436543193 Eli McMakin

    I love the idea of standards for PHP. And I like a lot of the suggestions. However, the braces on their own line for methods and classes has me scratching my head. What is the official reasoning behind this?

    • http://twitter.com/GaryJ Gary Jones

      It helps them to stand out from the stuff that happens inside the methods – if, foreach etc.

      Remember, that the PSRs are a summary of what the assessed frameworks were using – so the majority of decisions were taken on the majority usage from those.

      • http://www.facebook.com/people/Eli-McMakin/1436543193 Eli McMakin

        OK, that is a fair reason. I kind of like the braces not on their own line because it saves space, but I will have to give the PSR way a try and see how I like it. Thank you.

  • Patkos Csaba

    Great article. I did not know about PSRs, they look like a great guideline. PSR-2 is a little bit too extreme for me but I still mostly agree with it.

  • http://jarrydcrawford.com/ Jarryd

    In regards to working with WordPress either with a plug-in or just templating; would you follow the WordPress Coding Standards or the PSR?

    • http://twitter.com/WouterJNL Wouter J

      In the ideal world, the WordPress CS should extend the PSR. For instance, this is done in the Symfony CS.

    • http://www.facebook.com/people/Eli-McMakin/1436543193 Eli McMakin

      WP has their own coding standards that are not currently in alignment with PSR.

  • lsmith77

    Its telling how the main topic in the comments is tabs vs. spaces. If that is all that can be criticized about PSRs, then I guess things are going pretty well.

    • Eugene OZ

      Nope, it’s not only. PSR-3 is a pretty example, why all these PSR except PSR-0 is fucking annoying nothing.

      • rmwebs

        PSR is annoying as hell. But do you see a better option on the horizon? As it stands, PHP has been a complete shambles for years. Poor internal practices, really dumb management, and terrible code.

        Finally we’re at a stage where PHP is getting to the point where its actually no longer considered to be the overused, underpowered language. Things like namespaces have really helped there.

        The big issue we still have is the code. We all code differently – that shouldnt be the case. Sure, thats why we all learnt PHP, it allowed us to write code how we want. But it just doesn’t work. We’ve all been on github looking for a bit of code to do something, only to find its messy as fuck.

        With the likes of PSR we can make sure that EVERYONE rights their code in a consistant way.

        In a nutshell: Tough shit, conform or face problems – thats whats happening.

        For what it’s worth, I hated the idea. I did however (reluctantly) switch to spaces last month and to be honest, you dont even notice if you use something like sublime. Do I still think spaces suck? Yes. Simply because I have _ALWAYS_ used tabs. However it gets to a point where you have to just say ‘fuck it’ and conform.

  • kasakka

    I would never go for camelCase in PHP. I find that my_function_name (underscore separators) is generally more readable. I mean we already have stuff like recursiveIteratorIterator which would be far more readable as recursive_iterator_iterator.

    And spaces instead of tabs? Hell no!

    Also I have no problems using different conventions for different languages. I find camelCase fits Javascript quite nicely for some reason, perhaps due to its lack of $ signs or something.

    • David

      I prefer camelCase. Almost all the other programming languages use camelCase. TBH, it’s cleaner.

    • http://www.facebook.com/roosterjm2k2 Joshua McDonald

      my_function_name looks like amateur hour to me… it’s tonka.

      Underscores have meaning in most langs, and conven meaning in all langs. A ‘de facto’ standard that exists in about any language i’ve worked in is _s at the beginning of private members. That, and when i see underscores in any other var, I assume its a constant.

      The fact of the matter is that pretty much any modern language, or modern framework, sets the standard for camelCasing … and camelCasing is just as easy to read, so I fail to see the argument.

    • http://twitter.com/philsturgeon Phil Sturgeon

      my_function_name() is still perfectly valid in PSR code. It’s only method names that are camelCase, just like the core of PHP.

  • dlsniper

    Before posting yet another rant about PSR-1 and PSR-2, please read this: http://florinpatan.ro/2013/01/18/this-is-php-why-do-we-need-coding-style-standards/

  • http://www.facebook.com/goldnetonline Temitayo B. Akeem

    Looking at PSR-0, I have been implementing __autoload() for while now but the issue I have got is implementing it according to standard, I have my own way of doing this but I seem not to get the PHP5 namespace and use syntax as they are used frequently in symfony2, although symfony2 with the help of composer has done the job but I believe as a good developer, I should be able to handle it myself.

    As for the other PSR standards, they wouldn’t be a problem, would they?

    Temitayo Akeem @Goldnetonline do follow me on twitter please

    • dlsniper

      Here’s some food for thought about PSR-0.

      You might be a good/great/the ultimate developer. You may even have your won autoloader written specially for your projects that you just copy paster from one project to another. That’s great.

      But do you remember what happens when you try to interface Zend Framework 1.X with Symfony 1.X with a set of random libraries and so on? Biig problems for your autoloader.

      Namespaces are great for this as they allow classes to be mapped to folders via this standard and makes everyone adopting it a bit more happy as it’s dead simple on how to name your classes, namespaces and so on.

      As a developer, I always like to focus on implementing my project rather that be careful on details like how the autoloader is managed and by whom and the easier I get to swap between projects, the better I can focus on my things.

      If for some reason the autoloader I use happens to be broken, speed/functionality/something else then I’ll just try and fix it and submit a patch to the developer as well.

      Just my view on things :)

      • mattsah

        Yeah, I do have my own autoloader written specially for my own projects… and you’d be amazed to see that it actually has PSR-0 compatibility. This is primarily because I was given a brain clever enough to understand that PSR-0 is a terrible idea and that I would much rather define my namespaces in a way that makes sense for the code and architecture and then tell my autoloader how to find them as opposed to letting my autoloader determine how I structure my entire application.

        Thanks for playing.

      • mattsah

        Clarification needed… it also supports any number of other “standards.” For example, if I write a forum application which requires say 3 – 4 models (forum model, thread model, post model, user model) my models are much more likely to be placed in a /models/ directory with the vendor and module coming after… i.e. /models/dotink/forum and the namespace is most likely just DotinkForum not DotinkForumModels.

        This is the benefit of writing an autoloader that works to load code as opposed to writing code that works with an autoloader.

      • dlsniper

        You know, I don’t see your name on FIG mailing list (maybe I didn’t think of all the combinations from your nick here, or real name) but if you think it sucks so much, why don’t you go on the mailing list and rise the issue in a fashionable manner, explain your point of view and give a possible solution?

        And great for you, you’ve written your autoloader, great news! We all did. And you know what? I’m glad I can use Composer to generate the autoloader and leave me coding in my ignorance about the flaws it has. It just brings much more value for me to follow a strange convention that to have my own strange convention and explain it to people every time.

        What I don’t get is why you used ‘autoloaders’ and ‘projects’ together. Does that mean that you created more that one autoloader? Does it mean you create one for each project? Does it mean that you still can’t find your way to define common classes namespaces/class names even after multiple projects and when you switch from a project to another everything changes? You said you are clever, figure out where this is going and why you should follow a standard defined by others, if the assumptions are correct that is ;)

        Sorry what? It breaks your architecture?! Seriously? Please give me an example that actually makes sense from an architecture point of view of how PSR-0 is a deal breaker for your application. Here and on PHP-FIG mailing list. Just ranting about it here makes your argument worthless and doesn’t help solving a potential problem for many other users.

        I’m not saying adopt the standards from PHP-FIG blindly. No. Just the opposite. Question them, their functionality, they way of doing things and if you find a problem with them, take it up to the developers so that they can be aware of it and fix it or help you find the problem in your approach if that is flawed. Help them with useful comments not random unexplained bashing.

  • http://twitter.com/rei_liit John Kevin Basco

    very nice article. In my opinion following standards will be better since we can use and share any packages available via composer. And it makes code more consistent and the developer that will inherit your code will have less headaches since we are following a standard.

  • Steve

    My reaction to the PSR are they are just suggestions. At the end of the day the point of standards is to take the obscurity away. Tabs or spaces? It doesn’t matter, just choose one and stick to it! The FIG chose spaces. Braces on the same line or next? So long as you’re consistent, it doesn’t really matter!

    If you don’t agree with what’s in the PSR-X then don’t implement them! Simple.

    • include

      Ok, i’ll take all my programing vicious, put it in a document, and try to force everyone to follow it for a non logical reason.

      Thats what PSR means for me.

      • http://twitter.com/Kleiram Ramon Kleiss

        How exactly does PSR force you to use it?

    • http://twitter.com/GaryJ Gary Jones

      You’re missing the point – the consistency shouldn’t just be between past you, present you and future you, but between you and all the other developers you might be working with, or complete strangers who want to work with your code in their app, or their code in your app.

  • goyote

    thank god it’s four spaces and not two

    • rmwebs

      yeah never understood how people can use 2. Bootstrap uses it and it looks messy as hell.

  • http://www.famesbond.com/ aditya menon

    Formatting style Standards are long to read and hard to stick with, but I’m trying my best… I especially get tripped up on the method naming conventions, I keep_using_underscores by force of habit! Gotta stop that. PSR is important, it’s a great thing to be able to say “we are sticking to PSR” to any new developer who walks in and not have to fight about code formatting style, nor have to write a lengthy document describing every single thing..

  • mattsah

    @dlsniper:disqus @lsmith77:disqus and others…

    For all those who are interested, I have collected my criticisms in a much fuller article: http://scriptogr.am/mattsah/post/a-useful-critique-of-psr-x

    In particular to Mr. Sniper — you have either misunderstood or purposefully misrepresented my position on interfaces. I apologize if you misunderstood, as that is my fault for not being clear enough.

    • dlsniper

      Sorry bro, had to write it here as well: After the long discussion on your blog it just seems that you are talking without reading the PSRs first and you just disagree with them even if you don’t understand them. While for PSR-3 there could be some valid arguing points, you all boil down to a mass of words that could put you up near sites like brazzers & co. and makes anyone who’d be wiling to engage with you in a normal discussion have second thoughts.

      Not only that but when faced with non-technical arguments that actually prove that you are wrong, you choose to ignore them. So be it. I won’t be polluting this thread anymore.

      Who wants to read something that takes about 1-2 hours and realize at the end that you’d rather invest more time in replying to someone who likes you blindly rather that reading the damn documentation will understand what I’m saying. (Hope you won’t delete the comments)

  • http://twitter.com/JonnoTheBonno John Crossley

    I agree with most of this it’s fine i suppose. But this “Code MUST use 4 spaces for indenting, not tabs” Not a change I know it may seem petty and minor but it drives me NUTS!

  • http://andrewensley.com/ Andrew

    Thank you for writing about this! I just switched an entire project to use PSR-2. I wish the conversation about these standards had been better publicized (why am I only finding out about it now!?). I would have loved to weigh in on tab indentation and control structure braces, but oh well. At least there’s a STANDARD now, and I can follow it. Very excited about this.

  • Cubicle Ninjas

    Rhetoric and rationality tend to blur together in these discussions. Which would you rather have, specs/styles/standards that everyone follows or the Wild West? At Cubicle Ninjas we strive to follow PHP standards whenever possible. I say ‘whenever possible’ because sometimes you inherit an old project and refactoring to match guidelines is counterproductive.

  • Raymaster

    hi, best tuto

  • lord-love-a-duck

    Hopefully what goes for Joe, also goes for Jill The Programmer :)

  • Rowend

    This is really good effort to make php community better

  • http://www.facebook.com/leonelsr Leonel Rocha

    I’d really like to see a PSR-2 CHEAT SHEET (Quick Reference, etc). I’d make one if my design skills weren’t the worst in the world…