composer拓展包开发

本文详细介绍如何使用Composer初始化项目,开发并发布PHP拓展包至GitHub,包括包名、描述、作者信息、稳定性设置、依赖管理及自动加载配置。同时,演示了一个简单的加法功能的实现与发布流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值