Home > Backend Development > PHP Tutorial > PSR-Basic Coding Standard in PHP

PSR-Basic Coding Standard in PHP

Linda Hamilton
Release: 2025-01-07 06:13:43
Original
202 people have browsed it

PSR-Basic Coding Standard in PHP

Ever wondered why some PHP codebases are a joy to work with while others feel like a maze? A lot of it comes down to following consistent coding standards. Let’s explore PSR-1, the foundation of modern PHP development that helps teams write cleaner, more maintainable code!

Overview of PSR-1 Rules

1. Files and Namespaces

  • Files MUST use only
  • Files MUST use only UTF-8 without BOM for PHP code
  • Files SHOULD either declare symbols (classes, functions, constants) OR cause side-effects (generate output, modify settings, etc.) but SHOULD NOT do both

2. Namespace and Class Names

  • Classes MUST be declared in StudlyCaps
  • Class constants MUST be declared in all upper case with underscore separators

3. Class Methods

  • Method names MUST be declared in camelCase

Practical Implementation

Let’s look at a correct PSR-1 implementation from our example repository:

 $id, 'name' => 'John Doe'];
    }
}





This example demonstrates:

  • Proper namespace declaration using StudlyCaps
  • Class name in StudlyCaps
  • Constants in uppercase with underscores
  • Method name in camelCase

Common Violations and Fixes

  1. Mixed Responsibilities

  2. Incorrect Naming

Integration with Modern PHP Tools

Our example repository includes setup for:

  • PHP_CodeSniffer for PSR-1 validation (composer check-style)
  • Automated style fixing (composer fix-style)
  • PHPUnit for testing implementations
  • Composer autoloading following PSR-4

Next Steps

In our next post, we’ll explore PSR-12, which extends these basic coding standards with more comprehensive style guidelines. This post is part of our PSR Standards in PHP series.

Resources

  • Official PSR-1 Specification
  • PHP_CodeSniffer PSR-1 Ruleset
  • Series Example Repository (v0.1.0 - PSR-1 Implementation)

The above is the detailed content of PSR-Basic Coding Standard in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template