PHP发布自己的composer包

1. 准备工作

注册 Github 账号 : https://github.com/
注册 Packagist 账号 : https://packagist.org/ (可以使用github账户登录)

2. 添加git仓库

2.1 创建 Github 仓库

并按要求填写信息

2.2 克隆到本地

1
git clone https://github.com/gouyuwang/lumen.git

2.3 初始化composer.json

1
composer init

接下来全部回车 (如果有依赖,则按需求搜索依赖包)

或者手动创建composer.json文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"name": "gouyuwang/lumen",
"description": "lumen helper",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "gouyuwang",
"email": "529156563@qq.com"
}
],
# 如果你的数据需要加上PHP版本,并加入了src目录 需要追加下面配置
"require": {
"php": ">=7.0",
"php-curl-class/php-curl-class": "^7.2"
},
"require-dev": {
"composer/composer": "^1.2",
"friendsofphp/php-cs-fixer": "~2",
"phpunit/phpunit": "^4.8.35 || ^5.7",
"php-curl-class/php-curl-class": "^7.2"
},
"autoload": {
"psr-4": {
"gouyuwang\\lumen\\": "src/"
}
}
}

2.4 初始化 .gitignore

文件内容

1
/vendor/

2.5 业务逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

namespace gouyuwang\lumen;

class Response
{
public static function echo ( $text)
{
header("Content-type:text/html");
echo $text;
exit;
}
}

注意:PHP文件书写几个要点

  • 文中出现的不管是系统还是依赖的class 都必须开头使用 use 引入
  • 命名空间是你的项目名称对应的目录 [git-username]/[文件目录]
  • 代码放入src 类名与文件名最好相同

2.6 文件目录结构

3. 上传至git

如果有sourcetree 可以忽略下面的提交命令

3.1 提交

1
2
3
4
5
git init
git add .
git commit -m "first commit"
git remote add origin gouyuwang@github.com:gouyuwang/lumen.git
git push origin master

3.2 打tag

为什么要打tag?

tag相当于你的项目到了一个新的阶段,不再是开发版,否则使用

1
composer require gouyuwang/lumen @dev #其中 `@dev` 必不可少

查看最新提交的版本号

1
git log --oneline --decorate --graph

打tag

1
2
3
git tag v1.1 61d974a  // 在某个commit 上打tag

git push origin test_tag // 提交到线上库

删除 tag

1
2
3
git tag -d v1.1 // 删除某个commit 上的tag

git push origin :refs/tags/v1.1 // 提交到线上库

4. 提交packageist

访问并登陆:https://packagist.org

点击右上角的 submit , 输入你的git地址 : https://github.com/gouyuwang/lumen.git

点击 check, 完成后点击 submit 即提交完成

5. 检出依赖包

1
composer require gouyuwang/lumen

如果报错:

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

可能是你的tag没打成功,或者打成功后,并没有同步到国外服务器,请耐心等待

替代方案:

1
composer require gouyuwang/lumen @dev

现在你可以在项目中使用你写的依赖库了

关注作者公众号,获取更多资源!
赏作者一杯咖啡~