当前位置: 首页 > 工具软件 > Packagist > 使用案例 >

PHP:发布一个composer包到Packagist

施子民
2023-12-01

more-echo-php

a demo for PHP composer

一个PHP的composer包发布示例

1、初始化项目

mkdir more-echo-php

cd more-echo-php

# 初始化项目, 填写好项目的信息
$ composer init

项目目录

$ tree -I vendor
.
├── README.md
├── composer.json
└── src
    └── EchoText.php

composer.json

{
    "name": "mouday/more-echo",
    "description": "a demo for Composer",
    "type": "library",
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "Mouday\\MoreEcho\\": "src/"
        }
    },
    "authors": [
        {
            "name": "pengshiyu",
            "email": "1940607002@qq.com"
        }
    ],
    "require": {}
}

src/EchoText.php

<?php


namespace Mouday\MoreEcho;

/**
 * a demo for php composer
 * Class EchoText
 * @package Mouday\MoreEcho
 */
class EchoText
{
    public static function echoText($text)
    {
        echo $text;
    }
}

发布项目

  1. 将项目提交到github
  2. 将项目发布到packagist,点击submit输入github的项目地址

发布包地址:

使用发布的包

安装包

composer require mouday/more-echo

示例

<?php

require './vendor/autoload.php';

use  Mouday\MoreEcho\EchoText;

EchoText::echoText('Hello World!');
// Hello World!

问题

1、提示composer.json找不到

[RuntimeException]                                                                                    
  No composer.json present in the current directory (./composer.json), 
  this may be the cause of the following exception. 
echo '{}' > composer.json

2、包不存在

通常我们使用的是阿里云的镜像地址,刚提交的包,可能没有及时同步,可以临时设置一下包下载地址

$ composer config repo.packagist composer https://packagist.org/

3、版本号找不到

  [InvalidArgumentException]                                                                            
  Could not find a version of package mouday/more-echo matching your minimum-stability (stable). 
  Require it with an explicit version constraint allowing its desired stability. 

给项目打一个版本号的标签

git tag 1.0.0
 
git push --tag 

参考
php composer Packagist 创建第一个自己的包
101- composer [packagist]包制作(入门篇)

 类似资料: