插件开发实战


插件需求

要求开发一个独立的插件,插件最终以packagist包的形式呈现,插件功能如下:

  • 提取一个网页中的所有图片,并以数组的形式返回。
  • 对于形如 http://domain.com/image.jpg 格式的资源直接返回。
  • 对于以 Data URL scheme 格式开头的 data:image/png;base64 资源转换成图片二进制流返回。

插件名称

PHPCreeper-Plugin-ConvertDataURLSchemeImage

插件API

convertImage ($source = '')
@param  string  $source  源数据包,一般指HTML源码
@return array

插件目录

PHPCreeper-Plugin-ConvertDataURLSchemeImage
├── composer.json
├── ConvertDataURLSchemeImage.php
└── README.md

创建composer包

#切换到插件根目录
cd /path/to/PHPCreeper-Plugin-ConvertDataURLSchemeImage;

#引入爬山虎引擎
composer require blogdaren/phpcreeper

#配置命名空间
{
    "autoload": {
        "psr-4": {
            "PHPCreeperPlugin\\": "./"
        }
    }
}

#重载autoload
composer dumpautoload

编写插件逻辑

<?php
namespace  PHPCreeperPlugin;

use PHPCreeper\Kernel\Slot\PluginInterface;

class ConvertDataURLSchemeImage implements PluginInterface 
{
    protected $phpcreeper;

    public function __construct($phpcreeper)
    {
        $this->phpcreeper = $phpcreeper;
    }

    public static function install($phpcreeper, ...$args)
    {
        $phpcreeper->inject('convertImage', function($source = ''){
            return (new ConvertDataURLSchemeImage($this))->convertImage($source);
        });
     }

    public function convertImage($source = '')
    {
        if(empty($source)) return [];

        $rule = [['img', 'src']];
        $images = $this->phpcreeper->extractor->setHtml($source)->setRule($rule)->extract();

        $new_images = [];
        foreach($images as $k => $image)
        {
            if(preg_match("/^data:image\/(.*);base64,(.*)/is", $image[0], $matches)) 
            {
                $new_images['binary'][$k] = base64_decode($matches[2]);
            }
            else
            {
                $new_images['url'][$k] = $image[0];
            }
        }

        return $new_images;
     }
}

发布插件到packagist

git提交成功后即可同步发布到packagist

项目中引入插件

composer require blogdaren/PHPCreeper-Plugin-ConvertDataURLSchemeImage

项目中安装插件

<?php 
use PHPCreeper\Kernel\PHPCreeper;
use PHPCreeperPlugin/ConvertDataURLSchemeImage;

PHPCreeper::installPlugin(ConvertDataURLSchemeImage::class);

$downloader->onDownloaderStart = function($downloader){
    $source = $downloader->readDownloadData('http://www.mafengwo.cn/mdd/citylist/21536.html', true);
    $downloader->convertImage($source);
};
Free Web Hosting