如何开发 Laravel 扩展包并发布到 Composer

开发扩展包

我们来做一个根据第一个字符或者汉字生成头像的laravel扩展包。其实原理就是我们自己去写一个服务提供者,把服务提供者配置到app/providers数组中。

1.第一步现在自己项目中跟目录创建packages/cxp/avatar/src

2.修改 composer.json

 
"psr-4": {
    "App\\": "app/",
    "Cxp\\Avatar\\": "packages/cxp/avatar/src/"
}
  1. 执行composer dumpautoload

  2. src 目录创建 Avatar.php 具体代码

 
 
/**
 * Created by PhpStorm.
3
 * User: mac
4
 * Date: 2019-01-10
5
 * Time: 14:06
6
 */
7
namespace Cxp\Avatar;
8
use Illuminate\Config\Repository;
9
class Avatar {
10
    protected $config;
11
    /**
12
     * 构造方法
13
     */
14
    public function __construct(Repository $config)
15
    {
16
        $this->config = $config->get('avatar');
17
    }
18
    /**
19
     * 生成图像
20
     * @return resource 图片资源
21
     */
22
    private function generate($name)
23
    {
24
        // 创建图片资源
25
        $img_res = imagecreate($this->config['width'], $this->config['height']);
26
        // 背景颜色
27
        $bg_color = imagecolorallocate($img_res, mt_rand(120, 190), mt_rand(120, 190), mt_rand(120, 190));
28
        // 文字颜色
29
        $font_color = imagecolorallocate($img_res, mt_rand(190, 255), mt_rand(190, 255), mt_rand(190, 255));
30
        // 填充背景色
31
        imagefill($img_res, 1, 1, $bg_color);
32
        // 计算文字的宽高
33
        $pos = imagettfbbox($this->config['size'], 0, $this->config['font_file'], mb_substr($name, 0, 1));
34
        $font_width = $pos[2] - $pos[0] + 0.32 * $this->config['size'];
35
        $font_height = $pos[1] - $pos[5] + -0.16 * $this->config['size'];
36
        // 写入文字
37
        imagettftext($img_res, $this->config['size'], 0, ($this->config['width'] - $font_width) / 2, ($this->config['height'] - $font_height) / 2 + $font_height, $font_color, $this->config['font_file'], mb_substr($name, 0, 1));
38
        return $img_res;
39
    }
40
    /**
41
     * 输出图片(默认输出到浏览器,给定输出文件位置则输出到文件)
42
     * @param string|false $path 保存路径
43
     */
44
    public function output($name, $path = false)
45
    {
46
        $img_res = $this->generate($name);
47
        // 确定输出类型和生成用的方法名
48
        $content_type = 'image/' . $this->config['type'];
49
        $generateMethodName = 'image' . $this->config['type'];
50
        // 确定是否输出到浏览器
51
        if (!$path) {
52
            header("Content-type: " . $content_type);
53
            $generateMethodName($img_res);
54
        } else {
55
            $generateMethodName($img_res, $path);
56
        }
57
        // 释放图片内存
58
        imagedestroy($img_res);
59
    }
60
}
  1. 再src下创建config 目录来存取我们的配置参数文件如config/avatar.php
 
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-01-10
 * Time: 14:28
 */
return   [
    'type' => 'png', // jpeg|png|gif|bmp
    'width' => '100',
    'height' => '100',
    'size' => '26',
    'font_file' => public_path() . '/fonts/WawaSC-Regular.otf',
];
  1. 在src创建AvatarProvider.php即服务提供者。供ioc容器注册
 
namespace Cxp\Avatar;
use Illuminate\Support\ServiceProvider;
class AvatarProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // 发布配置文件
        $this->publishes([
            __DIR__.'/config/avatar.php' => config_path('avatar.php'),
        ]);
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('avatar', function ($app) {
            return new Avatar($app['config']);
        });
    }
}
  1. 如果想使用门脸,可以在src目录下创建Facades目录,提供门脸
 
namespace Cxp\Avatar\Facades;
use Illuminate\Support\Facades\Facade;
class Avatar extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'avatar';
    }
}

使用扩展包

到此我们开发就完成了,那改怎么使用了。

  1. 先发布配置文件在config目录下面
 
php artisan vendor:publish
  1. 在app/config目录注册我们的服务提供者和门脸类
 
'providers' => [
    Cxp\Avatar\AvatarProvider::class,
]
'aliases' => [
    'Avatar' => Cxp\Avatar\Facades\Avatar::class,
]
  1. 程序中使用
 
Avatar::output('赵','zhao.png');

发布扩展包

1.在avatar目录执行composer init,生成composer.json

 
{
    "name": "cxp/laravel-avatar",
    "description": "laravel avatar",
    "license": "MIT",
    "authors": [
        {
            "name": "cxp1539",
            "email": "457714145@qq.com"
        }
    ],
    "autoload": {
      "psr-4": {
        "Cxp\\Avatar\\": "src"
      }
    },
    "require": {}
}

2.在github创建个项目,将avatar目录的代码推送到github上。

3.打开https://packagist.org/ 注册个账号,提交git的地址就可以了。

示例代码下载链接

posted on 2020-04-27 17:02  爱漂泊人生  阅读(654)  评论(0编辑  收藏  举报

导航