Why is underscore converted to directory separator in the PSR-0 standard?
Asked Answered
P

3

6

The PSR-0 (https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) standard specifies that an underscore in the class name should be converted to a directory separator in the corresponding file name.

To me this does not seem to be a good idea as it creates lots of errors when someone who does not know the standard innocently uses an underscore in the class name and suddenly the autoloader cannot find the class and all sort of weird errors appear (see this stackoverflow issue for example: Symfony2.1 mapping error: class_parents())

So I guess there must be some kind of reason (historical compatibility with some library?) for this "feature". My question is: does anyone know why this was introduced in the PSR-0 standard?

Peril answered 27/7, 2012 at 22:0 Comment(0)
C
6

Underscores were used in the times that PHP didn't yet support namespaces. A "correct" organized project follows the convention of namespacing the files the same way as the directory structure.

It is just some general "rule" to organize files in a project.

So if you have a directory structure of:

root
  Name
    Package
      MyClass.php

People used to do:

class Name_Package_MyClass {}

But now that we have namespaces it becomes:

namespace Name\Package;

class MyClass { }

It is just coding style guideline which ensures that everybody does the same thing.

So what PSR-0 does is map both the old and the new style of namespacing to a filename.

Curriery answered 27/7, 2012 at 22:2 Comment(0)
F
1

PHP supports namespaces since version 5.3, earlier the most common convention was to use underscore as namespace (directory) separator, e.g.: My_Project_ClassName was mapped as /path/to/my/My/Project/ClassName. I believe that backwards compatibility is the main reason.

Forayer answered 27/7, 2012 at 22:5 Comment(0)
S
1

Keep in mind that the PSR-0 standard was written for a few specific projects and not necessarily the best option for your own project. As it says on their site: "If other folks want to adopt what we’re doing they are welcome to do so, but that is not the aim." PSR-0 is very restrictive, I wouldn't choose to use it just because other people are. Consider what you actually want from your project and whether it will be beneficial for you.

Sillabub answered 15/4, 2013 at 8:24 Comment(3)
Thank Tom, but PSR-0 is becoming the defacto standard for lots of projects (Symfony, for example), so sometimes you are just forced to use itPeril
@Tom B what you sugges to use then, instead? ThanksFirelock
Whatever meets the needs of the project. If you're using composer, any format it can use, if not, any method that works for the project.Sillabub

© 2022 - 2024 — McMap. All rights reserved.