Listening to the Words

TP5composer包开发的问题

昨天为tp5开发了一个composer包用来处理xss安全漏洞,其中也遇到了不少问题.

包地址:https://github.com/jeristiano/think-purifier

使用方法: composer require jeristiano/thinkphp-purifier

打包

按照composer开发流程,开发了此包上传到了package.org网站,结果执行时:

composer require jeristiano/thinkphp-purifier

[InvalidArgumentException]
Could not find package jeristiano/think-purifier at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

《TP5composer包开发的问题》

原因是:我的包还没有在github上发布正式(release),这个时候还是开发版本dev-master.应该加上dev-master版本

但是,为了使用必须发布一个正式版.

发布版本

去github发布一个版本,首先发布一个tag,然后发布版本.具体步骤可参照:

提交PHP组件到Packagist 发布自己的Composer包

tp5包的配置文件

如何在包安装的时候自动在extra/目录下生成配置文件?

 "extra": {
    "think-config": {
      "purifier": "src/config.php"
    }
  }

试了很多次,都没有成功,最后研究了发现:

 "require": {
    "php": ">=5.4.0",
    "topthink/think-helper": ">=1.0.4",
    "topthink/think-installer": ">=1.0.10",
  },

安装包依赖于topthink/think-installer安装器,安装器的作用是:

在包更新时执行plugin.php

<?php

namespace think\composer;

use Composer\Composer;
use Composer\Installer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;

class Plugin implements PluginInterface
{
    public function activate(Composer $composer, IOInterface $io)
    {
        $manager = $composer->getInstallationManager();

        //框架核心
        $manager->addInstaller(new ThinkFramework($io, $composer));

        //单元测试
        $manager->addInstaller(new ThinkTesting($io, $composer));

        //扩展
        $manager->addInstaller(new ThinkExtend($io, $composer));

    }
}

接着在ThinkExtend类下,只有包的类型是”think-extend”,时才会执行copyExtraFiles方法,composer.json的extra配置文件复制到extra目录下.


public function supports($packageType) { return 'think-extend' === $packageType; } $this->copyExtraFiles($package);

这个功能是根据composer官方提供的接口功能实现的,首先要实现这三个接口

use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;

文章在此 :(设置和使用自定义安装类型
)https://docs.phpcomposer.com/articles/custom-installers.html

使用方式

创建自己的包时,如果需要在安装时,在extra创建类config.php等配置文件,只需要在composer.json文件配置:”type”:”think-extend”,并在extra下配置文件名就可以了.

{
  "name": "jeristiano/think-purifier",
  "description": "Thinkphp 5 HtmlPurifier Package",
  "license": "Apache-2.0",
  "type":"think-extend",//最重要的配置
  "authors": [
    {
      "name": "jeristiano",
      "email": "jeremykuang@foxmail.com"
    }
  ],

  "require": {
    "php": ">=5.4.0",
    "topthink/think-helper": ">=1.0.4",
    "topthink/think-installer": ">=1.0.10",
    "ezyang/htmlpurifier": "4.10.*"
  },

  "autoload": {
    "psr-4": {
      "Jeristiano\\Purifier\\": "src/"
    },
    "files": [
      "src/common.php"
    ]
  },

  "extra": {
    "think-config": {
      "purifier": "src/config.php" //文件名会是 purifier.php
    }
  }
}

点赞