OctoberCMS如何使用Laravel開發(fā)拓展包

到現(xiàn)在為止婿牍,我還在為自己當(dāng)初大多數(shù)人都無法正常訪問安裝Octobercms的情況下選擇了OctoberCMS而慶幸,當(dāng)時選擇OctoberCMS除了其方便的特性和眾多的插件之外隐绵,還基于其是基于Laravel開發(fā)的,而Laravel的生態(tài)也是大勢所趨。

而后在開發(fā)過程中越來越證明我的判斷是對的介蛉,每當(dāng)業(yè)務(wù)邏輯需要一個新功能時爆阶,我基本都能找到合適的輪子并迅速上線燥透,真正地專注于業(yè)務(wù)邏輯。

下面講一講在Octobercms中如何如何引入Laravle生態(tài)中的開發(fā)拓展包

分兩種情況

分為兩種情況辨图,一種是全局安裝班套,需要在octobercms的根目錄引入composer,還有一種是在自己的插件目錄局部引入故河,局部引入的好處是不用動全局的任務(wù)文件吱韭。

下面我們以https://github.com/mewebstudio/Purifier為例來實例講解下。

相關(guān)環(huán)境:

  • October最新版(laravel5.*內(nèi)核)
  • PHP7.0
  • HTMLPurifier laravel表單過濾插件(https://github.com/mewebstudio/Purifier

注其它不同版本和環(huán)境也可參考同樣的流程鱼的。

一理盆、在全局安裝方式

準(zhǔn)備工作

全局安裝需要你先把Octobercms的在線安裝與管理模式全部改為composer來安裝與維護。
如果你一開始是基于composer命令行安裝(參看https://octobercms.com/docs/console/commands#console-install-composer)的凑阶,那么恭喜你猿规,可以直接引入Laravel包了;
如果你一開始是用的在線自動安裝的話那還有點小糾結(jié)宙橱,這里不展開說了姨俩,請對照官網(wǎng)自行操作(參看https://octobercms.com/docs/console/commands#console-install-composer)。

《如何在既有經(jīng)典安裝方式的項目上引入composer來管理》引自官網(wǎng)
To use composer with an October instance that has been installed using the Wizard installation, simply copy the tests/ directory, composer.json file and server.php file from GitHub into your October instance and then run composer install.

如何安裝

那么進入到這一步就相對簡單了养匈,直接參考laravel包的安裝說明即可

1哼勇、在octobercms的根目錄直接用命令引入包
composer require mews/purifier

或者,如果出現(xiàn)下面的錯誤則可以用編輯composer配置文件呕乎,再更新的方式

This package can be installed via Composer by requiring the mews/purifier package in your project's composer.json:

source-json
{
    "require": {
        "laravel/framework": "~5.0",
        "mews/purifier": "~2.0",
    }
}

再運行composer updatecomposer install积担,如果不也什么意外就安裝好了,再接著就是如何調(diào)用了猬仁。

重點一般來說Laravel 5.0以上的很多插件引入時會自動修改配置文件帝璧,但october好像并不認(rèn),需要手動配置修改文件config/app.php如下兩處湿刽。

修改config/app.php 的providers的烁,加入HTMLPurifier服務(wù)

    'providers' => [
        // ...
        Mews\Purifier\PurifierServiceProvider::class,
    ]

修改config/app.php 中的aliases配置

    'aliases' => [
        // ...
        'Purifier' => Mews\Purifier\Facades\Purifier::class,
    ]

發(fā)布配置文件
修改完配置文件后就要生成插件相關(guān)文件了,再在命令行輸入:
php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider"

安裝完畢诈闺。

2渴庆、引入laravel插件到octobercms開發(fā)文件中
在octobercms的相關(guān)文件頂部直接引入就行

//引入laravel插件Invite
use Invite;

二、在Octobercms插件開發(fā)目錄獨立引入

在octobercms的插件中可以為每一個當(dāng)前開發(fā)的插件單獨地寫composer文件來管理依賴,這樣就可以避免影響到全站文件襟雷,方便管理了刃滓,下面為譯文,因原文的說明也有點亂耸弄,故修正下放在這里咧虎,沒時間翻譯了,以后再整理吧计呈。

簡單地說明下流程砰诵,就是直接在octobercms的插件目錄中直接配置composer.json文件來引入,這點很簡單捌显,難的是如何引入這個插件茁彭。
composer.json寫法參考:

{
  "name": "luketowers/oc-laravelpackagesexample-plugin",
  "type": "october-plugin",
  "description": "OctoberCMS plugin for demonstrating the use of Laravel Packages within October plugins",
  "homepage": "https://github.com/LukeTowers/oc-laravelpackagesexample-plugin",
  "authors": [
    {
      "name": "Luke Towers",
      "email": "octobercms@luketowers.ca"
    }
  ],
  "require": {
    "mews/purifier": "~2.0"
  }
}

引入方法:

在當(dāng)前插件根目錄的Plugin.php文件中引入配置文件,并在其中用boot()方法來進行調(diào)用苇瓣,記得尉间,別忘記plugin.php文件頂部文件的頂部包含必要的facades和命名空間偿乖,另外击罪,記得在正式請求路由之前運行boot()
Plugin.php文件寫法參考:

<?php namespace LukeTowers\LaravelPackagesExample;
use App;
use Config;
use System\Classes\PluginBase;
use Illuminate\Foundation\AliasLoader;
/**
 * Class Plugin
 */
class Plugin extends PluginBase
{
    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Laravel Packages Example',
            'description' => 'OctoberCMS plugin for demonstrating the use of Laravel Packages within October plugins',
            'author'      => 'Luke Towers',
            'icon'        => 'icon-leaf'
        ];
    }
    /**
     * 在請求路由之前運行 Runs right before the request route
     */
    public function boot()
    {    
        // Setup required packages
        $this->bootPackages();
    }
    
    /**
     * Boots (configures and registers) any packages found within this plugin's packages.load configuration value
     *
     * @see https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-plugins
     * @author Luke Towers <octobercms@luketowers.ca>
     */
    public function bootPackages()
    {
        // Get the namespace of the current plugin to use in accessing the Config of the plugin
        $pluginNamespace = str_replace('\\', '.', strtolower(__NAMESPACE__));
        
        // Instantiate the AliasLoader for any aliases that will be loaded
        $aliasLoader = AliasLoader::getInstance();
        
        // Get the packages to boot
        $packages = Config::get($pluginNamespace . '::packages');
        
        // Boot each package
        foreach ($packages as $name => $options) {
            // Setup the configuration for the package, pulling from this plugin's config
            if (!empty($options['config']) && !empty($options['config_namespace'])) {
                Config::set($options['config_namespace'], $options['config']);
            }
            
            // Register any Service Providers for the package
            if (!empty($options['providers'])) {
                foreach ($options['providers'] as $provider) {
                    App::register($provider);
                }
            }
            
            // Register any Aliases for the package
            if (!empty($options['aliases'])) {
                foreach ($options['aliases'] as $alias => $path) {
                    $aliasLoader->alias($alias, $path);
                }
            }
        }
    }
}

接著建立一個配置文件config/config.php
格式如下:

<?php return [
    // This contains the Laravel Packages that you want this plugin to utilize listed under their package identifiers
    'packages' => [
        'mews/purifier' => [
            // 這里的配置一般在laravel拓展插件的安裝說明里面有Service providers to be registered by your plugin
            'providers' => [
                '\Mews\Purifier\PurifierServiceProvider',
            ],
            
            // 這里的配置一般在laravel拓展插件的安裝說明里面有Aliases to be registered by your plugin in the form of $alias => $pathToFacade
            'aliases' => [
                'Purifier' => '\Mews\Purifier\Facades\Purifier',
            ],
            
            // 下邊配置插件的命名空間The namespace to set the configuration under. For this example, this package accesses it's config via config('purifier.' . $key), so the namespace 'purifier' is what we put here
            'config_namespace' => 'purifier',
            
            // 下邊定義的是Laravel包自己原有的配置贪薪,直接把目標(biāo)Laravel包中的配置文件拷過來就行媳禁,如本例中對應(yīng)的是https://github.com/mewebstudio/Purifier/blob/master/config/purifier.php
            // The configuration file for the package itself. Start this out by copying the default one that comes with the package and then modifying what you need.
            'config' => [
                'encoding'      => 'UTF-8',
                'finalize'      => true,
                'cachePath'     => storage_path('app/purifier'),
                'cacheFileMode' => 0755,
                'settings'      => [
                    'default' => [
                        'HTML.Doctype'             => 'XHTML 1.0 Strict',
                        'HTML.Allowed'             => 'div,b,strong,i,em,u,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]',
                        'CSS.AllowedProperties'    => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
                        'AutoFormat.AutoParagraph' => true,
                        'AutoFormat.RemoveEmpty'   => true,
                    ],
                    'test'    => [
                        'Attr.EnableID' => true
                    ],
                    "youtube" => [
                        "HTML.SafeIframe"      => 'true',
                        "URI.SafeIframeRegexp" => "%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/)%",
                    ],
                ],
            ],
        ],
    ],
];


引入原文:

當(dāng)我在OctoberCMS中開發(fā)插件的時候,有過很多次想在其中使用Laravel開發(fā)拓展包的沖動画切,但問題是……

Several times while developing plugins for October, I've needed to include Laravel Packages in the plugin. The problem with doing this is that these packages assume that one will be able to configure them at a project level with things like config files for that specific package that get published to the config folder, or service providers and aliases that need to be registered with the application before you can use them.

I've written a blog post about how to deal with these packages within your October plugins in a clean and easy to use way. You can view the post here https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-cms-plugins/

作者寫了兩篇文章關(guān)于如何在octobercms中使用laravel拓展包的文章竣稽。

http://octobercms.com/forum/post/how-to-use-laravel-packages-in-october-plugins
https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-cms-plugins/

正文如下:
How to use Laravel Packages in OctoberCMS Plugins

This is just a quick guide on how to easily include Laravel Packages in OctoberCMS plugins.

Laravel Packages are often more complicated than simple classes that you can include in your project wherever. They can offer several things that are relatively easy to manage within a barebones Laravel application such as configuration files, service providers, and aliases; however things get slightly more complicated when you wish to use these packages within an October plugin.

The first thing that you’ll need to do in order to use a Laravel Package within your plugin is to require it via composer. Create a composer.json file in your plugin’s folder, and then add the packages you wish to use to the require object. An example of a composer.json for an October CMS plugin that requires a Laravel Package is below:

{
  "name": "luketowers/oc-laravelpackagesexample-plugin",
  "type": "october-plugin",
  "description": "OctoberCMS plugin for demonstrating the use of Laravel Packages within October plugins",
  "homepage": "https://github.com/LukeTowers/oc-laravelpackagesexample-plugin",
  "authors": [
    {
      "name": "Luke Towers",
      "email": "octobercms@luketowers.ca"
    }
  ],
  "require": {
    "mews/purifier": "~2.0"
  }
}

After you add your packages to composer.json, run composer update from the root of your project; this will pull those dependencies into your project so that you can use them. No need to run composer update or install from your plugin folder itself, if your plugin is being submitted to the October CMS marketplace the marketplace will generate the vendor folder for your plugin automatically.

現(xiàn)在,要做拓展包的初始設(shè)置/安裝了霍弹,你不能僅僅只運行默認(rèn)的擴展包安裝命令就完事兒毫别,你需要注冊service providers和aliases,然后典格,也還要提供一個方法給你的plugin插件岛宦,用來管理拓展包的配置文件。所有這些工作都可以在Octobercms的插件項目中相對輕松地完成耍缴,但是當(dāng)您想要確保您的插件可以實際用于其他人的項目時砾肺,就會遇到棘手的問題。

Now, as far as package initial setup / installation goes, you can’t just run the default installation commands for the package and be done, you need to register service providers and aliases, and then also provide a method for your plugin to manage the configuration of that package. All of these things can be done within an October project relatively painlessly, but the tricky bit comes when you want to make sure that your plugin can actually be used on other people’s projects.

但不要害怕防嗡,因為OctoberCMS包含了好幾種簡單的方法來動態(tài)注冊包的各個組件变汪。下面是我創(chuàng)建的一個方法,它可以方便地給你的plugin插件項目注冊任何的Laravel拓展包蚁趁。將此方法放置在當(dāng)前插件根目錄的Plugin.php文件中裙盾,然后從插件的boot()方法來調(diào)用(同樣在Plugin.php中操作)。

Never fear however, as October includes several easy ways to dynamically register the various components of the package. Below is a method that I’ve created that will easily register any Laravel packages for your plugin. Place this method in your plugin’s Plugin.php file, and then call it from the plugin’s boot() method (also in Plugin.php).

要確保你的plugin.php文件的頂部包含必要的facades,參考下面的寫法:
Also ensure that your Plugin.php includes the necessary facades at the top of the file below the namespace declaration as below:

use App;
use Config;
use Illuminate\Foundation\AliasLoader;

/**
 * Boots (configures and registers) any packages found within this plugin's packages.load configuration value
 *
 * @see https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-plugins
 * @author Luke Towers <octobercms@luketowers.ca>
 */
public function bootPackages()
{
    // Get the namespace of the current plugin to use in accessing the Config of the plugin
    $pluginNamespace = str_replace('\\', '.', strtolower(__NAMESPACE__));
    
    // Instantiate the AliasLoader for any aliases that will be loaded
    $aliasLoader = AliasLoader::getInstance();
    
    // Get the packages to boot
    $packages = Config::get($pluginNamespace . '::packages');
    
    // Boot each package
    foreach ($packages as $name => $options) {
        // Setup the configuration for the package, pulling from this plugin's config
        if (!empty($options['config']) && !empty($options['config_namespace'])) {
            Config::set($options['config_namespace'], $options['config']);
        }
        
        // Register any Service Providers for the package
        if (!empty($options['providers'])) {
            foreach ($options['providers'] as $provider) {
                App::register($provider);
            }
        }
        
        // Register any Aliases for the package
        if (!empty($options['aliases'])) {
            foreach ($options['aliases'] as $alias => $path) {
                $aliasLoader->alias($alias, $path);
            }
        }
    }
}

現(xiàn)在你可以通過在你的插件的配置文件中包含這些包來加載任何的拓展包了番官。
Now, you can load any packages you want by including them in your plugin’s configuration file, which is located here: /plugins/vendorName/pluginName/config/config.php.

任何在vendorName.pluginName::packages配置文件中發(fā)現(xiàn)的包都將自動加載童芹。
Any packages found in the ‘vendorName.pluginName::packages’ config value will be loaded.

下邊是一個用來加載 mews/purifier Laravel package的config.php的寫法示例:

Below is an example of a config.php file that is configured to load the mews/purifier Laravel package.

現(xiàn)在,您可以通過將它們包括在你的插件的配置文件中來加載任意的包了鲤拿,該文件位于這里:
/plugin s/vendorName/pluginName/config/config.php假褪。
config/config.php

所有的包,只要在vendorName.pluginName::packages配置了值的近顷,都會被加載生音。
下面是一份config.php的配置文件示例,該文件被配置為加載mews/purifier Laravel package的laravel包窒升。

<?php return [
    // This contains the Laravel Packages that you want this plugin to utilize listed under their package identifiers
    'packages' => [
        'mews/purifier' => [
            // Service providers to be registered by your plugin
            'providers' => [
                '\Mews\Purifier\PurifierServiceProvider',
            ],

            // Aliases to be registered by your plugin in the form of $alias => $pathToFacade
            'aliases' => [
                'Purifier' => '\Mews\Purifier\Facades\Purifier',
            ],

            // The namespace to set the configuration under. For this example, this package accesses it's config via config('purifier.' . $key), so the namespace 'purifier' is what we put here
            'config_namespace' => 'purifier',
            
            // The configuration file for the package itself. Start this out by copying the default one that comes with the package and then modifying what you need.
            'config' => [
                'encoding'      => 'UTF-8',
                'finalize'      => true,
                'cachePath'     => storage_path('app/purifier'),
                'cacheFileMode' => 0755,
                'settings'      => [
                    'default' => [
                        'HTML' => [
                            'Doctype'             => 'XHTML 1.0 Strict',
                            'Allowed'             => 'div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]',
                        ],
                        'CSS'  => [
                            'AllowedProperties'   => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
                        ],
                        'AutoFormat' => [
                            'AutoParagraph' => true,
                            'RemoveEmpty'   => true,
                        ],
                    ],
                    'test'    => [
                        'Attr' => ['EnableID' => true]
                    ],
                    "youtube" => [
                        "HTML" => ["SafeIframe" => 'true'],
                        "URI"  => ["SafeIframeRegexp" => "%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/)%"],
                    ],
                ],
            ],
        ],
    ],
];

文件的源碼參考
https://github.com/LukeTowers/oc-laravelpackagesexample-plugin

內(nèi)容有些亂缀遍,給自己做個記號,下次再整理了饱须。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末域醇,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蓉媳,更是在濱河造成了極大的恐慌譬挚,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件酪呻,死亡現(xiàn)場離奇詭異减宣,居然都是意外死亡,警方通過查閱死者的電腦和手機玩荠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進店門漆腌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人阶冈,你說我怎么就攤上這事闷尿。” “怎么了女坑?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵填具,是天一觀的道長。 經(jīng)常有香客問我堂飞,道長灌旧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任绰筛,我火速辦了婚禮枢泰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铝噩。我一直安慰自己衡蚂,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著毛甲,像睡著了一般年叮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上玻募,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天只损,我揣著相機與錄音,去河邊找鬼七咧。 笑死跃惫,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艾栋。 我是一名探鬼主播爆存,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蝗砾!你這毒婦竟也來了先较?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤悼粮,失蹤者是張志新(化名)和其女友劉穎闲勺,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體矮锈,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡霉翔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了苞笨。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡子眶,死狀恐怖瀑凝,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情臭杰,我是刑警寧澤粤咪,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站渴杆,受9級特大地震影響寥枝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜磁奖,卻給世界環(huán)境...
    茶點故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一囊拜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧比搭,春花似錦冠跷、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽抄囚。三九已至,卻和暖如春橄务,著一層夾襖步出監(jiān)牢的瞬間幔托,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工蜂挪, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留柑司,地道東北人。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓锅劝,卻偏偏與公主長得像攒驰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子故爵,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,884評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Getting Started Use the Current Stable Version (7.1) Buil...
    Leonzai閱讀 1,946評論 0 3
  • 原文鏈接 必備品 文檔:Documentation API:API Reference 視頻:Laracasts ...
    layjoy閱讀 8,607評論 0 121
  • 是什么 如果你知道yum玻粪、apt-get、npm诬垂、bower等命令中的一種或者多種劲室,那么,你也能很快知道compo...
    旱魃一樣閱讀 3,131評論 0 9
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理结窘,服務(wù)發(fā)現(xiàn)很洋,斷路器,智...
    卡卡羅2017閱讀 134,656評論 18 139
  • 一年一度的高考落下了帷幕隧枫,在這落幕時刻喉磁,有人歡喜有人憂。歡喜的當(dāng)然是覺得考得好的人官脓,憂愁當(dāng)然是那些覺得考得很差的人...
    胡義華閱讀 243評論 0 0