PSR PHP naming standard

PSR PHP naming standard

About PSR

PHP developers created many professional tools to make coding easier. One of them is PSR standard. This standard contains recommendations how to organize classes, interfaces and traits naming in your code.

Namespaces

In PHP you can use namespaces to isolate your code in a virtual environment where you are free to create classes, interfaces, traits or variables with any name you want. This is very useful in large projects with many external dependencies. For example, you want use class Class_A created by another developer in your code. But you already have Class_A created by yourself. In this case you can refactor your code – change the class’s name. But better option is to use namespaces.

namespace MyExistingProject;
class Class_A{
....
}

Now you can create a new instance of your class this way:

$instance = new \MyExistingProject\Class_A();

And an instance of external class

$instance = new Class_A();
Directory tree

The main idea in PSR is that your namespace structure must match the structure of the directory tree where you store your code. For example, you have a folder structure like this:

/Models/User.php

/Models/Order.php

/Controllers/UserOrderController.php

/index.php

In this case your classes should be stored in respective files:

User -> User.php

Order -> Order.php

UserOrderController -> UserOrderController.php

Namespaces of a class should reflect path to the file, e.g.

\MyProject\Models\User

\MyProject\Models\Order

\MyProject\Controllers\UserOrderController

Note that folders and file names MUST be SAME with namespaces!

Autoloading

Another purpose of PSR usage is improved autoloading. Since your code is well organized with PSR requirements, you can use autoloading scripts to load required source files in your project. Check out your index.php without autoloader:

<?php

require_once "Models/User.php";

require_once "Models/Order.php";

require_once "Controllers/UserOrderController.php";

....

?>

and with autoloader

<?php

require_once "autoloader.php"

...

?>

As you can see, requirement management became easier.

Autoloader files usually are included in modern frameworks like Laravel.

Conclusion

Using of namespaces and PSR standard will allow you to use any naming you want, make your code more readable and improve requirement management.

Author: vlad