Table of Contents
要求
例子
下划线在命名空间和类名中的使用
扩展例子
SplClassloader的实现
扩展实现
扩展阅读
Posts related to PHP的PSR-0命名标准
Home php教程 php手册 PHP的PSR-0命名标准

PHP的PSR-0命名标准

Jun 06, 2016 pm 08:12 PM
php psr name standard

PSR 是Proposing a Standards Recommendation(提出标准建议)的缩写,是由 PHP Framework Interoperability Group( PHP 通用性框架小组,简称 PHP-FIG )发起的,通过他们命名就可以看出,这是个主要是针对框架通用性而做努力的开放性小组,他们的在Github

PSR是Proposing a Standards Recommendation(提出标准建议)的缩写,是由PHP Framework Interoperability Group(PHP通用性框架小组,简称PHP-FIG)发起的,通过他们命名就可以看出,这是个主要是针对框架通用性而做努力的开放性小组,他们的在Github上有自己的仓库地址,目前只有一个被接受的标准,那就是PSR-0标准,标准定义了PHP自动加载的命名规范和文件路径规范。 针对PSR-0标准主要提到了以下几点:

要求

  • 一个完全合格的命名空间和类名必须有以下的结构“\\(\)*”
  • 每个命名空间必须有顶级的命名空间(“提供者”)
  • 每个命名空间可以有任意多个子命名空间
  • 每个命名空间在被从文件系统加载时必须被转换为“操作系统路径分隔符”(DIRECTORY_SEPARATOR?)
  • 每个“_”字符在“类名”中被转换为DIRECTORY_SEPARATOR 。“_”符号在命名空间中没有这个含义
  • 符合命名标准的命名空间和类名必须以“.php”结尾来加载文件
  • 提供商名称,命名空间,类名可以由大小写字母组成,其中命名空间和类名是大小写敏感的以保证多系统兼容性
  • 如果文件不存在需要返回false

例子

\Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php
\Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php
\Zend\Acl => /path/to/project/lib/vendor/Zend/Acl.php
\Zend\Mail\Message => /path/to/project/lib/vendor/Zend/Mail/Message.php
Copy after login

下划线在命名空间和类名中的使用

\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php
\namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php
Copy after login

设置这个标准是为了保证最基本的共同点。你可以通过实现5.3的SplClassLoader来测试这个标准。

扩展例子

提供一个函数来展示如何使用上述标准。

function autoload($className)
{
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strripos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    require $fileName;
}
Copy after login

SplClassloader的实现

接下来这个gist实现了SplClassLoader可以加载你按照上面标准来实现的通用类库,这是5.3里面推荐的加载方式。

http://gist.github.com/221634

扩展实现

因为这个标准提到了如果文件不存在的时候应该范围false,但是在上面函数的例子中并没有实现该机制,所有有人实现了优化的SplClassLoader。

class ClassLoader
{
    /**
     * @var array Contains namespace/class prefix as key and sub path as value
     */
    protected $paths;
    /**
     * Construct a loader instance
     *
     * @param array $paths Containing class/namespace prefix as key and sub path as value
     */
    public function __construct( array $paths )
    {
        $this->paths = $paths;
    }
    /**
     * Load classes/interfaces following PSR-0 naming
     *
     * @param string $className
     * @return null|boolean Null if no match is found, bool if match and found/not found.
     */
    public function load( $className )
    {
        if ( $className[0] === '\\' )
            $className = substr( $className, 1 );
        foreach ( $this->paths as $prefix => $subPath )
        {
            if ( strpos( $className, $prefix ) !== 0 )
                continue;
            $lastNsPos = strripos( $className, '\\' );
            $prefixLen = strlen( $prefix ) + 1;
            $fileName = $subPath . DIRECTORY_SEPARATOR;
            if ( $lastNsPos > $prefixLen )
            {
                // Replacing '\' to '/' in namespace part
                $fileName .= str_replace(
                    '\\',
                    DIRECTORY_SEPARATOR,
                    substr( $className, $prefixLen, $lastNsPos - $prefixLen )
                ) . DIRECTORY_SEPARATOR;
            }
            // Replacing '_' to '/' in className part and append '.php'
            $fileName .= str_replace( '_', DIRECTORY_SEPARATOR, substr( $className, $lastNsPos + 1 ) ) . '.php';
            if ( ( $fileName = stream_resolve_include_path( $fileName ) ) === false )
                return false;
            require $fileName;
            return true;
        }
    }
}
Copy after login

引用地址:https://github.com/andrerom/fig-standards/blob/psr2/proposed/PSR-2.md

标准对于开发者来说是一个好事,如今已经越来越多的开源项目加入了这个标准Pear2、PHPBB、Composer、Packagist、Joomla、Drupal、Symfony、CakePHP、Doctrine2等等,采用同样标准的项目可以无缝的接入,做为开发者最好要尝试并接收一个好的标准。

扩展阅读

PHP官方关于SplClassLoader的RFC:https://wiki.php.net/rfc/splclassloader

PHP标准化组织论坛:https://groups.google.com/forum/?fromgroups#!forum/php-standards

VI快捷键

VI快捷键

如何修改、扩展并重写Magento代码

如何修改、扩展并重写Magento代码

Magento购物车Checkout Onepage页面的SaveBilling处理过程

Magento购物车Checkout Onepage页面的SaveBilling处理过程

Magento裁剪后的略缩图背景填充颜色的修改

Magento裁剪后的略缩图背景填充颜色的修改

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

See all articles