Laravel5.4 框架與 Laravel-admin 整合 Markdown 編輯器

十里長亭發表於2018-12-12

本文將使用Laravel5.4框架,開發裝置為windows,使用Homestead 環境。

一、安裝Laravel專案


1.安裝專案:


cd ~/Homestead && vagrant up
vagrant ssh
vagrant@homestead:~$ cd Code
vagrant@homestead:~/Code$ composer create-project laravel/laravel digtime

// 或者指定版本
composer create-project --prefer-dist laravel/laravel digtime "5.5.*"

2.homestead.yaml配置


➜ ~ atom ~/.homestead/Homestead.yaml
---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Code
      to: /home/vagrant/Code

sites:
    - map: digtime.app # <--- 這裡,第四個專案
      to: /home/vagrant/Code/digtime/public # <--- 這裡

databases:
    - digtime

variables:
    - key: APP_ENV
      value: local

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp

3.重啟vagrant


修改完 Homestead.yaml檔案後,需要重新載入配置檔案資訊才能生效。

➜  ~ cd Homestead
➜  Homestead git:(7924ab4) vagrant reload --provision

4.修改hosts配置檔案


Hosts配置域名在mac的位置: /etc/hosts

192.168.10.10 digtime.app

5.通過域名訪問


digtime.app

6.快速進入專案


cd ~/Homestead && vagrant up
vagrant ssh
cd ~/Code/digtime

二、安裝專案需要的資源


1.npm安裝前端包


npm install

2.artisan 生成表


執行所有未執行的遷移

php artisan migrate

回滾上一次的遷移

vagrant@homestead:~/Code/digtime$ php artisan migrate:rollback

3. artisan 命令生成許可權


php artisan make:auth

4. 修改User位置


Laravel為我們預設建立的模型檔案放置在 app資料夾下,為了更符合 MVC模式的開發流程,本博文統一使用 app/Models資料夾來放置所有的模型檔案。現在讓我們先來建立一個 app/Models 資料夾,並將 User.php 檔案放置到其中。

$ mkdir app/Models
$ mv app/User.php app/Models/User.php

在執行完這一步的操作之後,我們還需要執行下面這兩個操作:

1、修改 User.php 檔案,更改namespace為我們新建立的資料夾路徑:
app/Models/User.php

<?php
namespace App\Models;
.

2、全域性更改 App\User 為 App\Models\User,在Atom中使用快捷鍵 shift + cmd(ctrl) + f 來進行全域性搜尋替換的操作。

完成之後,點選右下角的Replace All按鈕。

三、github 託管專案


git 初始化

vagrant@homestead:~/Code/digtime$ git init
Initialized empty Git repository in /home/vagrant/Code/digtime/.git/
vagrant@homestead:~/Code/digtime$ git add -A
> git commit -m "Initial commit"

// 將專案推到github上
> git remote add origin git@github.com:corwien/digtime.git
> git push -u origin master

// 新增分支
> git checkout master
> git checkout -b users

四、webpack打包資源


有關Laravel5.4webpack使用,請看我的這篇博文:
Laravel5.4新特性-Laravel-mix的使用

Mix是位於 Webpack 頂層的配置層,所以要執行 Mix 任務你只需要在執行包含在預設 package.json檔案中的其中某個 NPM 指令碼即可:

// 1.安裝package.json 包
npm install

// 2.執行所有 Mix 任務...
npm run dev

// 執行所有 Mix 任務並減少輸出...
// npm run production

// 3.監控前端資源改變
npm run watch
監控前端資源改變

五、密碼重置郵件傳送


對密碼重置郵件傳送進行重構,使用sendCloud進行傳送。
App\Models\User.php 使用者 Model 方法中重寫sendPasswordResetNotification($token)傳送郵件的方法:

 /**
     * 重寫重置密碼的郵件傳送通知,覆蓋zhihu_app_reset_password底層的傳送方法
     * 對這個類進行重寫: \Illuminate\Contracts\Auth\PasswordBroker
     *  $user->sendPasswordResetNotification(
     *   $this->tokens->create($user)
     *   );
     * 類檔案:Passwords\PasswordBroker
     * @param $token
     */
    public function sendPasswordResetNotification($token)
    {
        // 重構傳送郵件
        (new UserMailer())->resetPassword($token, $this->email);
    }

IlluminateAuthPasswordsPasswordBroker.php

 /**
     * Send a password reset link to a user.
     *
     * @param  array  $credentials
     * @return string
     */
    public function sendResetLink(array $credentials)
    {
        // First we will check to see if we found a user at the given credentials and
        // if we did not we will redirect back to this current URI with a piece of
        // "flash" data in the session to indicate to the developers the errors.

        // 根據傳遞過來的email獲取使用者資訊
        $user = $this->getUser($credentials);

        if (is_null($user)) {
            return static::INVALID_USER;
        }

        // Once we have the reset token, we are ready to send the message out to this
        // user with a link to reset their password. We will then redirect back to
        // the current URI having nothing set in the session to indicate errors.
        $user->sendPasswordResetNotification(
            $this->tokens->create($user)
        );

        return static::RESET_LINK_SENT;
    }

IlluminateAuthPasswordsCanResetPassword.php

 /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPasswordNotification($token));
    }

最底層的傳送郵件方法:
IlluminateAuthNotificationsResetPassword.php

 /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line('You are receiving this email because we received a password reset request for your account.')
            ->action('Reset Password', route('password.reset', $this->token))
            ->line('If you did not request a password reset, no further action is required.');
    }

六、自定義函式方法


app目錄下,建立共用的函式檔案Support/helpers.php

建立方法檔案之後,需要在composer.json檔案中自動載入:

 "autoload": {
        "files":[
            "app/Support/helpers.php"
        ],

    },

然後執行 composer 重新載入方法:

> composer dump-autoload

七、Markdown編輯器


http://editor.integ.me/ segmentfault 家的,解析庫也有:https://segmentfault.com/a/11...

https://laravel-china.org/top...

1.Markdown編輯器


Markdown編輯器:https://simplemde.com/

這個編輯器看起來挺不錯,很簡潔,我們可以整合在我們的專案中。

1.1 npm 安裝


npm install simplemde --save

1.2 引用

resources/assets/js/bootsrap.js 中引入剛下載的資源包:

// 引入markdown編輯器
window.simplemde = require('simplemde');

1.3 編譯靜態資源

使用命令編譯剛引入的資源,這樣才可以編輯在public/app.js中:

npm run dev

OK,這樣就引入到前端資原始檔中了

Demo:
demo.html

<!DOCTYPE html>  
<html>

    <head>
        <meta charset="utf-8" />
        <title>SimpleMDE Dome</title>
       <link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
       <script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
        <style type="text/css">
            body{
                background: #eaebec;
            }
            h1{
                font-size: 50px;
                text-align: center;
            }
            .container{
                background: #fff;
                width: 800px;
                padding: 20px;
                margin: 50px auto;
            }
        </style>
    </head>

    <body>

        <h1>SimpleMDE Dome</h1>

        <div class="container">
            <textarea name="" rows="" cols="" id="editor"></textarea>
        </div>

        <script type="text/javascript">
            // Most options demonstrate the non-default behavior
            var simplemde = new SimpleMDE({
                autofocus: true,
                autosave: {
                    enabled: true,
                    uniqueId: "editor01",
                    delay: 1000,
                },
                blockStyles: {
                    bold: "__",
                    italic: "_"
                },
                element: document.getElementById("editor"),
                forceSync: true,
                hideIcons: ["guide", "heading"],
                indentWithTabs: false,
                initialValue: "SimpleMDE Dome",
                insertTexts: {
                    horizontalRule: ["", "\n\n-----\n\n"],
                    image: ["![](http://", ")"],
                    link: ["[", "](http://)"],
                    table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
                },
                lineWrapping: false,
                parsingConfig: {
                    allowAtxHeaderWithoutSpace: true,
                    strikethrough: false,
                    underscoresBreakWords: true,
                },
                placeholder: "placeholder",
               /* previewRender: function(plainText) {
                    console.log(plainText)
                    return customMarkdownParser(plainText); // Returns HTML from a custom parser
                },
                previewRender: function(plainText, preview) { // Async method
                    setTimeout(function(){
                        preview.innerHTML = customMarkdownParser(plainText);
                    }, 250);

                    return "Loading...";
                },*/
                promptURLs: true,
                renderingConfig: {
                    singleLineBreaks: false,
                    codeSyntaxHighlighting: true,
                },
                shortcuts: {
                    drawTable: "Cmd-Alt-T"
                },
                showIcons: ["code", "table"],
                spellChecker: false,
                status: false,
                status: ["autosave", "lines", "words", "cursor"], // Optional usage
                status: ["autosave", "lines", "words", "cursor", {
                    className: "keystrokes",
                    defaultValue: function(el) {
                        this.keystrokes = 0;
                        el.innerHTML = "0 Keystrokes";
                    },
                    onUpdate: function(el) {
                        el.innerHTML = ++this.keystrokes + " Keystrokes";
                    }
                }], // Another optional usage, with a custom status bar item that counts keystrokes
                styleSelectedText: false,
                tabSize: 4,
                //toolbar: flase,
                //toolbarTips: false,
            });
        </script>

    </body>
</html>

1.4 在Laravel-admin中整合Simplemde編輯器

我們可以給下邊的laravel-admin後臺 整合該 Markdown 的編輯器。

Simplemde 是一個優秀簡潔的Markdown編輯器,如果laravel-admin 自帶的基於 ckeditor的編輯器元件使用上有問題,可以通過下面的步驟可以整合它,並覆蓋掉ckeditor

1.4.1 先下載前端庫檔案Simplemde

先下載前端庫檔案Simplemde, 解壓到目錄public/packages/admin/simplemde

1.4.2 新建元件類

然後新建元件類app/Admin/Extensions/Simplemde.php

<?php

namespace App\Admin\Extensions;

use Encore\Admin\Form\Field;

class Simplemde extends Field
{
    protected $view = 'admin::form.editor';

    protected static $css = [
        '/packages/admin/simplemde/dist/simplemde.min.css',
    ];

    protected static $js = [
        '/packages/admin/simplemde/dist/simplemde.min.js',
    ];

    public function render()
    {
        $this->script = <<<EOT

 var simplemde = new SimpleMDE({
               autofocus: true,
                autosave: {
                    enabled: true,
                    delay: 5000,
                    unique_id: "editor01",
                },
                spellChecker: false,
            });

EOT;
        return parent::render();

    }
}

1.4.3 註冊

然後註冊進laravel-admin,在 app/Admin/bootstrap.php 中新增以下程式碼:

<?php

/**
 * Laravel-admin - admin builder based on Laravel.
 * @author z-song <https://github.com/z-song>
 *
 * Bootstraper for Admin.
 *
 * Here you can remove builtin form field:
 * Encore\Admin\Form::forget(['map', 'editor']);
 *
 * Or extend custom form field:
 * Encore\Admin\Form::extend('php', PHPEditor::class);
 *
 * Or require js and css assets:
 * Admin::css('/packages/prettydocs/css/styles.css');
 * Admin::js('/packages/prettydocs/js/main.js');
 *
 */

// Encore\Admin\Form::forget(['map', 'editor']);

use App\Admin\Extensions\Simplemde;
use Encore\Admin\Form;

Form::extend('editor', Simplemde::class);

1.4.4 使用

// 這樣就可以使用我們上邊自定義的Simplemde Markdown編輯器了
$form->editor('content');

完整檔案

  /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Article::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('title', '標題')->rules('required|min:3');
            $form->text('subtitle', '副標題');

            $form->text('user_id', '作者ID')->default(4);
            $form->text('slug', 'Slug')->default('My-blog-4');
            $form->text('category_id', '分類ID')->default(1);
            $form->text('order', '排序')->default(1);
            $form->radio('is_excellent', '是否精華')->options(['F' => '否', 'T' => '是'])->default('T');

            // 圖片路徑為upload/images/
            $form->image('page_image', '上傳文章背景圖')->move('images', function($file){

                // 自定義檔名,時間戳+五個隨機字串+使用者ID
                $file_name =  date("Ymd") . str_random(6);
                return $file_name . "." . $file->guessExtension();
            });

            $form->datetime('published_at', '釋出作品時間')->format('YYYY-MM-DD HH:mm:ss');

            $form->display('created_at', trans('admin::lang.created_at'));
            $form->display('updated_at', trans('admin::lang.updated_at'));

            // 自定義的編輯器
            $form->editor('content')->rules('required|min:3');
        });
    }

2.Markdown解析類


segmentfault 的Markdown解析類:SegmentFault/HyperDown

Laravel 引入第三方類檔案,我們在app目錄下新建一個路徑,app/Markdown,並將下載的類檔案 Parser.php 放在該目錄下,然後再新建一個檔案,引用該類,這樣做的好處就是可以完全分離核心類檔案,如同合約contacts 一樣,如果以後我們的解析類變了,我們只需對核心類做改變,而其他應用的方法不需要再修改。

markdown.php 引用 parse.php 類:

<?php

namespace App\Markdown;

/**
 * Class Markdown
 *
 * @package \App\Markdown
 */
class Markdown
{
    protected $parser;

    /**
     * Markdown constructor.
     *
     * @param $parser
     */
    public function __construct(Parser $parser)
    {
        $this->parser = $parser;
    }

    public function markdown($text)
    {
        $html = $this->parser->makeHtml($text);

        return $html;
    }

}

在引用第三方類後,需要執行下面命令進行自動載入:

composer dump-autoload

使用方法:

<?php

protected $markdown;
public function __construct(Markdown $markdown)
{
   $this->markdown = $markdown;
}

// 解析Markdown 內容
$this->markdown->markdown($article->content);

3.Markdown語法高亮


找了一個非常簡潔的Markdown 樣式檔案,我放在了 Gist上,有需要的朋友可以看看:
Gist: corwien/Markdown.scss

將該檔案下載放在Laravel中 resources/assets/css/vendor/markdown.scss,然後在 resources/sass/app.scss中引入:

// Markdown

// 程式碼高亮
@import "./../css/vendor/highlight.min";

// 編輯器樣式檔案
@import "./../css/vendor/simplemde.min";

// 引入markdown樣式檔案
@import "./../css/vendor/markdown.scss";   

然後編譯前端資原始檔:

npm run dev

這樣,該markdwon樣式檔案就編譯到前端資原始檔中了。

我們可以在前端的內容欄位處引入 class="markdown" 樣式,然後看看渲染效果:
article.blade.php

    <div class="markdown" >
       {!! $article->content !!}
    </div>

程式碼塊是不是很簡潔清爽許多呢?

八、開源的管理後臺


我們可以在專案中引入開源的管理後臺,這樣可以大大的提高我們的專案開發速度,這裡推薦兩個非常強大的開源管理後臺。

1.Laravel-Administrator


【擴充套件推薦】管理員後臺快速生成工具 Administrator "增強版" 分享

專案GitHub地址:summerblue/administrator

該後臺非常好用,由Laravel-China 團隊維護開發,十分鐘就可以搭建起一個簡單的管理後臺:

2.laravel-admin


該管理後臺非常強大,使用Laravel AdminLTE開發,可以快速實現增刪改查功能及角色管理。

專案:GitHub地址: z-song/laravel-admin

Demo: 後臺使用者名稱:admin 密碼:admin

由於該前端資源有引入google地圖,所以,前端載入會非常慢,這裡我們對原始碼進行一下修改:
換掉谷歌的地圖,載入時間過長:
/vendor/encore/laravel-admin/src/Form/Field/Map.php

/**
     * Get assets required by this field.
     *
     * @return array
     */
    public static function getAssets()
    {
        // 本專案配置環境使用的語言包是zh-CN,'resources/lang/zh-CN/', 所以這裡對zh_CN做出修改【20170501】
        if (config('app.locale') == 'zh-CN') {
            $js = 'http://map.qq.com/api/js?v=2.exp';
        } else {
            $js = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key='.env('GOOGLE_API_KEY');
        }

        return compact('js');
    }

九、Markdown側邊欄生成


為了使我們的文章詳情頁更利於瀏覽,像SF一樣,有一個側邊導航欄,這裡我們使用一段js程式碼就可以輕鬆的實現該功能。

js程式碼:

<link rel="stylesheet" href="http://yandex.st/highlightjs/6.2/styles/googlecode.min.css">

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://yandex.st/highlightjs/6.2/highlight.min.js"></script>

<script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
 $(document).ready(function(){
      $("h2,h3,h4,h5,h6").each(function(i,item){
        var tag = $(item).get(0).localName;
        $(item).attr("id","wow"+i);
        $("#category").append('<a class="new'+tag+'" href="#wow'+i+'">'+$(this).text()+'</a></br>');
        $(".newh2").css("margin-left",0);
        $(".newh3").css("margin-left",20);
        $(".newh4").css("margin-left",40);
        $(".newh5").css("margin-left",60);
        $(".newh6").css("margin-left",80);
      });
 });
</script>
<div id="category"></div>

十里長亭

相關文章