国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Understanding PSR- The PHP Coding Style Guide

Understanding PSR- The PHP Coding Style Guide

Oct 22, 2024 am 06:11 AM

Understanding PSR- The PHP Coding Style Guide

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

  1. What is PSR-12?
  2. Why is PSR-12 Important?
  3. Key Rules of PSR-12
    • File Structure
    • Namespaces and Use Declarations
    • Classes and Methods
    • Control Structures
    • Comments and Documentation
  4. How to Apply PSR-12 in Your PHP Projects
  5. Tools to Help You Follow PSR-12
  6. 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;
    }
}




<h4>
  
  
  4. Control Structures
</h4>

<p>Control structures like if, for, and switch must follow certain rules:</p>

<ul>
<li>
<strong>Structure</strong>: There must be one space between the control keyword and the opening parenthesis. Curly braces {} must always be used, even for single-line statements.</li>
<li>
<strong>Indentation</strong>: All blocks inside control structures must be indented by one level (typically four spaces).
</li>
</ul>

<pre class="brush:php;toolbar:false">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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles