If you’ve been developing with PHP for a while, you've likely encountered the term PSR-12. It’s one of the most widely accepted coding standards in the PHP community and is aimed at ensuring consistency in PHP codebases across different projects. Whether you're working solo or as part of a team, following PSR-12 can make your code cleaner, more readable, and easier to maintain. In this blog, we'll break down what PSR-12 is, why it's important, and how you can apply it in your projects.
Table of Contents
- What is PSR-12?
- Why is PSR-12 Important?
-
Key Rules of PSR-12
- File Structure
- Namespaces and Use Declarations
- Classes and Methods
- Control Structures
- Comments and Documentation
- How to Apply PSR-12 in Your PHP Projects
- Tools to Help You Follow PSR-12
- Final Thoughts
What is PSR-12?
PSR-12 is a coding style guide for PHP, developed by the PHP-FIG (Framework Interoperability Group). It builds upon the previous PSR-2 standard, providing an updated set of rules that reflect modern PHP practices and improve consistency across codebases.
Think of PSR-12 as the blueprint for writing clean, readable, and maintainable PHP code. By following PSR-12, developers can ensure that their code adheres to a standardized structure, making it easier to collaborate with others and to work on open-source projects.
Why is PSR-12 Important?
Coding standards like PSR-12 aren't just about nitpicking over spaces and tabs. Here’s why they matter:
- Readability: Code that follows a standard style is easier to read, especially for developers new to a project.
- Collaboration: If everyone follows the same rules, working together becomes smoother and more efficient.
- Maintainability: Clean, consistent code is easier to debug, test, and extend over time.
- Interoperability: In open-source projects or when integrating third-party libraries, following a common standard ensures compatibility across different codebases.
Key Rules of PSR-12
Let’s dive into some of the key rules that PSR-12 lays out. While there are many smaller guidelines, here are the ones that stand out the most.
1. File Structure
- Opening Tag: PHP files must use the
- Encoding: Files must be encoded in UTF-8 without a BOM (Byte Order Mark).
- Line Length: Lines should not be longer than 120 characters, but lines up to 80 characters are preferred.
- Blank Lines: There should be no blank lines after the opening PHP tag or before the closing tag. Additionally, there must be a single blank line before return statements, and between method definitions.
2. Namespaces and Use Declarations
PSR-12 requires that namespaces and use declarations follow a specific order to improve clarity:
- Namespace Declaration: The namespace declaration must be the first line after the opening PHP tag. There must be one blank line after the namespace.
- Use Declarations: All use declarations must be grouped together after the namespace declaration and separated by a blank line. Additionally, there must be one blank line after the last use statement.
Example:
<?php namespace App\Controllers; use App\Models\User; use App\Repositories\UserRepository; class UserController { // Class implementation }
3. Classes and Methods
PSR-12 enforces some strict rules on how classes, properties, and methods should be declared:
- Class Declaration: The class keyword must be followed by a space, then the class name. Open curly braces { must be placed on the same line as the class declaration, with closing braces } on their own line.
- Properties: Visibility (public, protected, private) must be declared for all properties.
- Methods: Similar to class declarations, the function keyword must be followed by a space, then the method name. Visibility must be declared for all methods.
class UserController { private $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } }
4. Control Structures
Control structures like if, for, and switch must follow certain rules:
- Structure: There must be one space between the control keyword and the opening parenthesis. Curly braces {} must always be used, even for single-line statements.
- Indentation: All blocks inside control structures must be indented by one level (typically four spaces).
if ($user->isAdmin()) { echo "User is an admin"; } else { echo "User is not an admin"; }
5. Comments and Documentation
Comments are crucial for explaining why certain parts of the code exist. PSR-12 emphasizes the need for proper, clear comments.
- Block Comments: Use /* */ for multi-line comments, and place a blank line before the comment.
- Single-line Comments: Use // for inline comments, and ensure that comments are meaningful.
<?php namespace App\Controllers; use App\Models\User; use App\Repositories\UserRepository; class UserController { // Class implementation }
How to Apply PSR-12 in Your PHP Projects
To follow PSR-12 in your projects, you can manually adhere to the guidelines when writing code, but the best way to ensure compliance is by using automated tools.
First, get familiar with these general practices:
- Use consistent indentation: Four spaces are required for indentation.
- Limit line length: Try to keep your lines under 120 characters, although 80 characters are preferred for better readability.
- Organize code structure: Follow the rules for class declarations, visibility, and control structures.
Tools to Help You Follow PSR-12
Manually ensuring that your code follows PSR-12 can be time-consuming, but there are tools that can help you automate this process.
1. PHP_CodeSniffer
One of the most popular tools for ensuring your PHP code follows PSR-12 is PHP_CodeSniffer. It analyzes your code and points out where you're deviating from the standard.
To install and use it:
class UserController { private $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } }
Then, run it against your code:
if ($user->isAdmin()) { echo "User is an admin"; } else { echo "User is not an admin"; }
2. PHP CS Fixer
Another useful tool is PHP CS Fixer. It not only detects issues but can also fix your code to comply with PSR-12 automatically.
// Fetch user from the repository $user = $userRepository->find($id); /* * If user is not found, throw an exception. * This helps in handling invalid user IDs. */ if (!$user) { throw new NotFoundException(); }
Run the fixer with:
composer require "squizlabs/php_codesniffer=*"
3. PHPStorm
If you use PHPStorm, you can configure it to follow PSR-12. Go to Settings -> Editor -> Code Style -> PHP and set the standard to PSR-12.
Final Thoughts
Following PSR-12 in your PHP projects is about more than just adhering to arbitrary rules. It’s about making your code cleaner, more readable, and easier to maintain—whether you're working alone or with a team. By following PSR-12, you're not just writing code for yourself but for the entire PHP community.
Adopting this standard is a step towards writing professional, consistent, and maintainable PHP code. Use the tools mentioned to make the process easier, and watch how clean and organized your projects become!
Happy coding!
The above is the detailed content of Understanding PSR- The PHP Coding Style Guide. For more information, please follow other related articles on the PHP Chinese website!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
