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' <'[email protected]'>, n to skip]: nomandia <[email protected]>
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": "[email protected]"
        }
    ],
    "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": "[email protected]"
    }
  ],
  "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 [email protected]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章