Table of Contents
目录结构和初建准备
初始化 composer
文件自动加载 autoload
travis 测试集成
编写代码
编写单元测试
文档
发布到 github 和 Packagist
概括
参考文章
Home Backend Development PHP Tutorial Create PSR-4 Php package

Create PSR-4 Php package

Oct 23, 2020 pm 05:28 PM
php psr-4

Create PSR-4 Php package

【相关学习推荐:php图文教程

本文是帮助初学者搭建基础的 php composer 包, 本项目源码地址

  • github
  • packagist

目录结构和初建准备

首先创建一个目录来存放所有文件, 这里我 命名为 util-demo , 目录中需要包含两个目录 src/, tests/, 所有的代码需要放置到 src/ 目录, 所有的测试文件需要放置到 tests/ 目录

初始化文件夹, 并使用 git 初始化项目, 便于进行版本管理

$ mkdir util-demo
$ cd util-demo
$ git init复制代码
Copy after login

初始化 composer

这里假定你已经安装了 composer, 如果没有安装, 请到 getcomposer.org/download/ 进行安装

初始化并输入包名, 这里默认使用 duoli/util-demo 包名

$ composer init

Welcome to the Composer config generator  
                                            
This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [duoli/util-demo]: 
复制代码
Copy after login

输入描述

Description []: first util package demo复制代码
Copy after login

输入作者名称, n 跳过

Author [duoli <zhaody901@126.com>, n to skip]: 
复制代码
Copy after login

设定包的稳定版本, 默认是 stable, 详细查看 minimum-stability (root-only)

Minimum Stability []: 
复制代码
Copy after login

安装类型 : Package Type, 默认是 library

Package Type (e.g. library, project, metapackage, composer-plugin) []: 
复制代码
Copy after login

License, 协议, 关于协议部分, 你可以选择自己需要的协议, 阮老师这里有一个阅读指南, 可以进行参考 如何选择开源许可证?, 对于协议部分的写法可以参考 许可协议 license 这里

License []: 
复制代码
Copy after login

require

设定三方依赖, 表明当前项目/包是否有依赖于其他包进行开发, 这里选择 no,

Define your dependencies.

# 生产依赖
Would you like to define your dependencies (require) interactively [yes]? 
复制代码
Copy after login

require-dev

开发依赖, 这里我们加入 phpunit 作为单元测试依赖

Would you like to define your dev dependencies (require-dev) interactively [yes]?

Search for a package: phpunit

Found 15 packages matching phpunit

   [0] phpunit/phpunit 
   ...
   [14] brianium/paratest 

Enter package # to add, or the complete package name if it is not listed: 0
Enter the version constraint to require (or leave blank to use the latest version): 
Using version ^8.5 for phpunit/phpunit
Search for a package: 
复制代码
Copy after login

当不需要额外增加包的时候, 直接回车, 确认安装包依赖, 初始化完成

{
    "name": "duoli/util-demo",
    "description" : "first util package demo",
    "require-dev": {
        "phpunit/phpunit": "^8.5"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "duoli",
            "email": "zhaody901@126.com"
        }
    ],
    "require": {}
}

Do you confirm generation [yes]? 

Would you like to install dependencies now [yes]? yes
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 29 installs, 0 updates, 0 removals
  - Installing sebastian/version (2.0.1): Downloading (100%)         
  ......     
  - Installing phpunit/phpunit (8.5.8): Downloading (100%)         
sebastian/global-state suggests installing ext-uopz (*)
phpunit/phpunit suggests installing phpunit/php-invoker (^2.0.0)
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
5 packages you are using are looking for funding.
Use the `composer fund` command to find out more!复制代码
Copy after login

上边初始化完成之后, 我们文件目录应该如下所示

.
├── composer.json
├── composer.lock
└── vendor复制代码
Copy after login

作为包管理来讲, 我们需要忽略 composer.lockvendor 文件夹, 因为在项目中使用此包的时候会进行全局的安装, 不提交是为了不产生冗余代码.

我们加入 .gitignore 文件, 加入这两个文件夹的忽略, 另外由于要生成 phpunit 测试文件, 我们还需要加入 .phpunit.* , 我这里还额外加入了 IDE 的忽略

.gitignore

# ide
.idea

# project
composer.lock
vendor/

# phpunit
.phpunit.*复制代码
Copy after login

文件自动加载 autoload

autoload

这里是上边初始化没有提及到的, autoload 指定了包的加载方式, Composer 可以自动加载包内文件, 但是你需要指定你的文件的加载方式, 这里我们使用的是 psr-4 标准, 详细的规范可以阅读 PSR-4 自动加载规范

这里需要在 composer.json 中追加

   ...    "autoload": {        "psr-4": {            "Duoli\\UtilDemo\\": "src",            "Duoli\\UtilDemoTests\\": "tests"
        }
    }
   ... 
复制代码
Copy after login

因为这个加载是后续添加的, 想要识别需要我们手动运行下 composer dumpautoload, 这样才可以识别我们添加的命名空间映射

另这里我额外约定了一个测试的命名空间, 方便对测试文件进行命名空间的目录识别

travis 测试集成

如果打算在GitHub上托管包,一个不错优点是集成Travis CI,这是一个持续集成应用程序,它会自动运行单元测试文件. 当接受 pr 时,会非常有用,因为你可以快速查看是否所有的测试都通过验证。

要与 Travis 集成,添加一个名为 .travis.yml 的文件,并复制以下内容

language: php

php:
    – 7.0
    – hhvm

before_script:
    – composer self-update
    – composer install –prefer-source –no-interaction –dev

script: phpunit复制代码
Copy after login

在这里,不会深入讨论使用 Travis 的问题,但这应该是一个很好的开始,你可以自己来进行研究如何使用它.

编写代码

现在可以编写代码了, 打开 src 目录创建 File.php 文件, 复制如下代码

class File{    public function extension($filename)    {        return pathinfo($filename, PATHINFO_EXTENSION);
    }

}复制代码
Copy after login

如果你曾经查看过旧的 PHP 包源码,可能会发现一个 Duoli/UtilDemo 目录。PSR-4 不再使用嵌套的目录结构,而是允许直接在 src 目录下编写类

编写单元测试

现在我们已经编写了包源码,可以开始编写一些测试了。PHPUnit 需要一个名为 phpunit.xml 的文件来定义一些设置。在根目录中创建一个新的phpunit.xml文件,并复制以下代码:

<phpunit
    backupGlobals="false"
    backupStaticAttributes="false"
    bootstrap="vendor/autoload.php"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    processIsolation="false"
    stopOnFailure="false">
    <testsuites>
        <testsuite name="Duoli Util Test Suite">
            <directory suffix=".php">./tests/</directory>
        </testsuite>
    </testsuites></phpunit>复制代码
Copy after login

如果不熟悉这个文件中意思,不用担心,你无需关注设置了哪些内容(当前来讲), 这个文件只是定义一些设置和文件应该如何自动加载的约定.

接下来,在 tests 目录下,创建一个名为 StrTest.php的文件,并复制以下代码:

<?php namespace Duoli\UtilDemoTests;

use Duoli\UtilDemo\File;
use PHPUnit\Framework\TestCase;

class FileTest extends TestCase
{

    public function testExtension()
    {
        $extension = File::extension(&#39;readme.md&#39;);
        $this->assertEquals('md', $extension);
    }

}复制代码
Copy after login

打开命令行并运行:

$ ./vendor/bin/phpunit复制代码
Copy after login

PHPUnit 会自动运行测试,并给出一个绿色的 OK (1 test, 1 assertion) 输出。

在编写测试文件时,需要确保测试类继承了 PHPUnit\Framework\TestCase

文档

最后要做的是创建一个 Readme.md 的文档。如果打算在 GitHub上托管代码,这个文件会在代码页面显示出来,目的是描述包以及包如何工作.

还应该在源代码中包含一个许可证。默认情况下,你发布的任何东西都是你的版权所有,如果你想让其他人使用你的代码,你需要给它一个许可。一个好的选择是 MIT 许可

发布到 github 和 Packagist

现在已经完成了你的包,你可以将它推到 GitHub 和 Packagist。

GitHub 是一个托管的 git 存储库服务,它使得在软件协作变得非常容易。

Packagist 是查找和使用 PHP 包的服务商

要将代码推送到 GitHub,创建一个新的存储库, 然后设定 git 的远端, 将代码推上去即可, 命令是

$ git remote add origin git@github.com:username/demo.git  
$ git push -u origin master  
复制代码
Copy after login

在 Github 上集成 Packagist 和 Travis, 需要找到设置, 并且在  Webhooks & Services 部分找到这两个服务, 集成这两个服务需要授权 github 账户并且设置一些简单的步骤.

概括

如果以前从未开发过已发布的 php 包,那么需要考虑很多问题。然而,一旦你操作过不止一次就不至于这么复杂了.

PHP 的包结构非常简单,而 PSR-4 使其更加简单。一旦了解了该结构的每一部分是用于做什么,其他人阅读 PHP包就会容易很多.

参考文章

  • How to create a PSR-4 PHP package

相关学习推荐:php编程(视频)

The above is the detailed content of Create PSR-4 Php package. 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

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
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,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

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

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles