Composer 增加自己Laravel的扩展

Composer 增加自己Laravel的扩展

在日常的开发过程中,我们有时候会突发奇想,尝试封装自己的插件。通过本文的阅读相信你在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://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
# You may choose to ignore a library lock file http://getcomposer.org/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.phpcomposer.com/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

四、发布插件到 packagist

到 https://packagist.org/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://packagist.org/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
BTW

有时候无法从composer中下载自己的组件,这时候确认下你是否用了国内镜像,如果是会因为镜像不是最新的而无法更新,切回默认的就好了。

composer config -g repo.packagist composer https://packagist.org

如果不是频繁修改还是用国内的吧,毕竟等待也是一种折磨。

composer config -g repo.packagist composer https://packagist.phpcomposer.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值