PHP手把手教你发布自己的 Composer包
PHP手把手教你发布自己的 Composer包
文章目录
1. 准备工作
注册 Github 账号 : https://github.com/
注册 Packagist 账号 : https://packagist.org/
2. 添加git仓库
2.1 创建 Github 仓库
并按要求填写信息
2.2 克隆到本地
git clone https://github.com/friker/test.git
2.3 初始化composer.json
composer init
Pagekage name : friker/test
Descript []: php test script
Author: friker [email protected]
Mininum Stability []:
Package Type []: library
license []: MIT
接下来全部回车 (如果有依赖,则按需求搜索依赖包)
生成
{
"name": "friker/test",
"description": "php test script",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "friker",
"email": "[email protected]"
}
],
"require": {}
}
如果你的数据需要加上PHP版本,并加入了src目录 需要追加下面配置:
"require": {
"php": ">=5.5"
},
"autoload": {
"psr-4": {
"friker\\test\\": "src/"
}
}
2.4 初始化 .gitignore
文件内容
/vendor/
2.6 库文件echo.php
<?php
namespace friker\test;
class Echo
{
public function xml($data = array())
{
header("Content-type:application/json");
echo '<?xml version="1.0" encoding="utf-8"?>'
echo '<data>';
foreach($data as $k => $v){
echo "<{$k}>$v</$k>";
}
echo '</data>';
exit;
}
public function json($data = array())
{
header("Content-type:application/json");
echo json_encode($data);
exit;
}
}
注意:PHP文件书写几个要点
- 文中出现的不管是系统还是依赖的class 都必须开头使用
use
引入 - 命名空间是你的项目名称对应的目录
[git-username]/[文件目录]
- 代码放入
src
类名与文件名最好相同
2.6 文件目录
test |
src |
Echo.php
.gitignore
composer.json
README.md
3. 上传至git
如果有sourcetree
可以忽略下面的提交命令
3.1 提交
git init
git add .
git commit -m "提交第一版"
git remote add origin [email protected]:friker/test.git
git push origin master
3.2 打上tag
为什么要打tag?
tag相当于你的项目到了一个新的阶段,不再是开发版,否则使用
composer require friker/test @dev
其中 @dev
必不可少
git log --oneline --decorate --graph
- 5b1da02 提交第一版
git tag -a v1.0 5b1da02
4. 提交packageist
访问并登陆:https://packagist.org
点击右上角的 submit
, 输入你的git地址 :
https://github.com/friker/test.git
点击 check
,完成后点击 submit
即提交完成
5. 检出依赖包
composer require friker/test
如果报错:
[InvalidArgumentException]
Could not find a version of package friker/test matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.
可能是你的tag没打成功,或者打成功后,并没有同步到国外服务器,请耐心等待
替代方案:
composer require friker/test @dev
现在你可以在你的项目你 使用你的提交的依赖库了