composer的出现大大提升了开发的效率,当我们去开发什么功能的时候,大多时候我们都可以在composer仓库中找到相对应的轮子,来使用。
如果自己也想写轮子给广大的php开发者使用,那么就该学习一下composer包如何开发了

composer项目初始化

这里我创建的文件夹 math

composer init

Package name (<vendor>/<name>) [chaow/math]: smallk/math //包名 格式必须
Description []: math test // 描述
Author [, n to skip]:
 Invalid author string.  Must be in the format: John Smith <john@example.com>
Author [, n to skip]: smallk <396656156@qq.com>  //作者姓名和邮箱
Minimum Stability []: dev //迭代中
Package Type (e.g. library, project, metapackage, composer-plugin) []: library  //拓展包类型
License []: MIT //开源限制

Define your dependencies.

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

{
    "name": "smallk/math",
    "description": "math test",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "smallk",
            "email": "396656156@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {} //依赖其他拓展
}

Do you confirm generation [yes]? yes

设置自动加载路径

打开 composer.json 文件在后面添加自动加载的路径,这里使用 psr-4 规则,对应我们在math目录下建立src/Math目录,在Math文件夹中放我们的php文件

{
    "name": "smallk/math",
    "description": "math test",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "smallk",
            "email": "396656156@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Math\\": "src/Math/"
        }
    }
}

拓展包开发

Math目录中新建Math.php文件写一个简单的加法

<?php

namespace Math;
class Math
{
    public function sum($a,$b){

        return $a+$b;
    }
}

拓展包发布

将开发完的拓展包发布github上,如何将代码发布到github自行搜索

已经将本地math目录同步到github上,在本项目的设置中将私有仓库改为公有仓库

github账号授权登录composer网站,进行包的提交

  • 可能会出现包名重复异常,我们需要修改我们的包名
{
    "name": "superkingm/math", //全小写不能出现大写
    "description": "math test",
    "type": "library",
    "license": "MIT",
    "authors": [
        {
            "name": "superkingm",
            "email": "396656156@qq.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Math\\": "src/Math/"
        }
    }
}

再次提交,完成拓展包发布

拓展包使用

我们已经在composer上面发布了我们的拓展包,我们现在就去使用我们的拓展包

composer require superkingm/math dev-master

新建index.php文件使用拓展包中的类

<?php
require './vendor/autoload.php';
use Math\Math;
class Test{
    function one(){
        $math = new Math();
        echo $math->sum(10,20);
    }
}
$obj = new Test();
$obj->one();//页面打印30
  • 到这里我们的composer拓展包已经可以分享给其他人使用了
  • 下一篇:拓展包的自动更新与版本控制

本文地址:https://blog.csdn.net/weixin_43674113/article/details/107409503