分享

Composer 增加自己Laravel的扩展

 中间件 2020-09-24

在日常的开发过程中,我们有时候会突发奇想,尝试封装自己的插件。通过本文的阅读相信你在20分钟内就能掌握这种技巧,当然速度快慢取决于你的网络状况。截图比较麻烦我就直接堆代码了。另外,本文参考了 https://github.com/BroQiang/laravel-image

一、创建一个composer项目

生成 composer.json

# 创建一个二级目录
> mkdir nomandia/iimage
> cd nomandia/iimage
> composer init

  Welcome to the Composer config generator

This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [nomandia/iimage]: nomandia/iimage
Description []: Simple picture upload toolkit.
Author ['rootme' <'rootme@abc123.com'>, n to skip]: nomandia <nomandia@qq.com>
Minimum Stability []: 0.1 # 注意这里是默认的版本,会影响到composer的下载
 Invalid minimum stability "0.1". Must be empty or one of: stable, RC, beta, alpha, dev
Minimum Stability []: library # 不填就是library
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]? yes
# 这里定义一些依赖,根据自身情况调整。也可以跳过,然后修改composer.json
Search for a package: php
Enter the version constraint to require (or leave blank to use the latest version): ~7.1.0
Search for a package: laravel/framework
Enter the version constraint to require (or leave blank to use the latest version): ~5.5
Search for a package: inervention/image
# 拼写错误时也有提示
Found 8 packages matching inervention/image

   [0] intervention/image
   [1] intervention/imagecache
   [2] poznet/image
   [3] ostashevdv/yii2-image
   [4] finwe/phpstan-intervention-image
   [5] flexnst/laravel-image
   [6] spiral/intervention-image
   [7] hpkns/picturesque

Enter package # to add, or the complete package name if it is not listed: 0
Enter the version constraint to require (or leave blank to use the latest version): ~2.4
Search for a package: qiniu/php-sdk
Enter the version constraint to require (or leave blank to use the latest version): ~7.2
Search for a package:
Would you like to define your dev dependencies (require-dev) interactively [yes]?
Search for a package:

{
    "name": "nomandia/iimage",
    "description": "Simple picture upload toolkit.",
    "type": "library",
    "require": {
        "php": "~7.1.0",
        "laravel/framework": "~5.5",
        "intervention/image": "~2.4",
        "qiniu/php-sdk": "~7.2"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "nomandia",
            "email": "nomandia@qq.com"
        }
    ],
    "minimum-stability": "dev"
}

Do you confirm generation [yes]? yes

文件创建完毕可以执行:composer install 来安装依赖。

添加.gitignore

composer.phar
/vendor/
# Commit your application's lock file https:///doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
# You may choose to ignore a library lock file http:///doc/02-libraries.md#lock-file
# composer.lock

如果你直接在github上创建repository话会提示你创建 .gitignore

二、创建目录及文件

按照以下结构创建(这里本着最简单的实现原则)

> tree
> /home/nomandia/iimage
> ├───.gitignore
> ├───config
> ├──────iimage.php
> ├───src
> ├──────IImage.php
> ├──────IImageProvider.php
> ├───vendor # 执行composer install后生成,目前没有
> ├───composer.json
> ├───LICENSE
> ├───README.md

修改composer.json

注意 autoloadextra 项,详情可参考 http://docs./04-schema.html

{
  "name": "nomandia/iimage",
  "description": "Simple picture upload toolkit.",
  "require": {
    "php": "^7.1.0",
    "laravel/framework": "~5.5",
    "intervention/image": "~2.4",
    "qiniu/php-sdk": "~7.2"
  },
  "require-dev": {
    "php": "^7.1.0",
    "laravel/framework": "~5.5",
    "intervention/image": "~2.4",
    "qiniu/php-sdk": "~7.2"
  },
  "license": "MIT",
  "authors": [
    {
      "name": "nomandia",
      "email": "nomandia@qq.com"
    }
  ],
  "autoload": {
    "psr-4": {
      "Nomandia\\IImage\\": "src/"
    }
  },
  "extra": {
    "laravel": {
      "providers": [
        "Nomandia\\IImage\\IImageProvider"
      ]
    }
  }
}

接下来安装依赖,稍等片刻

composer install

三、调整文件

目前涉及到了3个文件:config/iimage.phpsrc/IImage.phpsrc/IImageProvider.php,根据作用类型分为:

  1. 自定义的配置文件
// file: config/iimage.php
<?php
return [
    'tmpPath'=>'/tmp'
];
  1. 实现体,具体业务类
// file: src/IImage.php
<?php
namespace Nomandia\IImage;

class IImage
{

    protected $config = [];

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

    public function initConfig()
    {
        $configs = config('iimage', []);
    }
    
    public function surpriseMe($name){
        echo $name, ", u're awesome."
    }
}
  1. 服务提供者,用于全局注册后调用
// file: src/IImageProvider.php

<?php

namespace Nomandia\IImage;

use Illuminate\Support\ServiceProvider;

class IImageProvider extends ServiceProvider
{
    public function boot()
    {
        // 复制自定义的文件到config目录
        if (!file_exists(config_path('iimage.php'))) {
            $this->publishes([
                dirname(__DIR__) . '/config/iimage.php' => config_path('iimage.php'),
            ], 'config');
        }
    }

    public function register()
    {
        $this->mergeConfigFrom(
            dirname(__DIR__) . '/config/iimage.php', 'iimage'
        );
    }
}

上传项目到 github

项目开发完毕后就传到github,这步很关键。

> git commit -m "im nb"
> git push origin master # or git push 

四、发布插件到 packagist

https:///packages/submit 去提交你的插件包即可。这里推荐注册一个和github一样的名字比较好。

测试下

> composer require nomandia/iimage

  [InvalidArgumentException]
  Could not find package nomandia/iimage at any version for your minimum-stability (dev). Check the package spelling or your minimum-stability

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader
] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

这里出现了版本的错误,原因是你的项目并未提供一个默认的版本号导致。你可以在 https:///packages/nomandia/iimage 这个页面看到项目的版本信息。要纠正这个错误我们只要增加一个版本号即可

> composer require nomandia/iimage dev-master
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing qiniu/php-sdk (v7.2.6): Loading from cache
  - Installing nomandia/iimage (dev-master 6a0aa40): Cloning 6a0aa40754 from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nunomaduro/collision
Discovered Package: intervention/image
Discovered Package: nomandia/iimage
Package manifest generated successfully.

如此这般便能在你的项目中使用自己的插件了,看!有木有成就感~!

// 你可以这样式的用
<?php
namespace App\Http\Controllers;

use Nomandia\IImage\IImage as Image;

class TestController extends Controller
{
    function index(){
        $v = new Image();
        $v->surpriseMe('Nomandia');
    }
}

有时候使用git提交时候会报SSL的错误,如:

> git push
git Unknown SSL protocol error in connection to github.com:443

# 这里强制关闭SSL安全链接
git config --global http.sslVerify false

# 另外切换账号也记录下
git config --global user.name nomandia
git config --global user.email nomandia@qq.com

五、项目更新自动发布到

  1. 到github.com/USERNAME/PROJECT,打开Settings选项页;
  2. 左侧菜单中选择 Integrations & services
  3. 增加一个名为:PackagistService
  4. 输入packagist 配置,如:账号、token、packagist地址,勾选Active项,然后提交表单即可。

六、常见问题

  • 更新异常时,尝试使用dev版本 composer require nomandia/iimage:dev-master,注意如果你不在github上发布release版本的话,那么dev-master将是默认版本。另外,不推荐指定你项目composer.json中最低接受的版本minimum-stability选项,这样的话其默认值是dev,可在一定程度上避免这种问题。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多