本文將使用Laravel5.4框架開發一個全新的博客,開發設備爲Mac,使用Homestead 環境,IDE 爲 Phpstorm。
> 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.*"
➜ ~ 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
修改完 Homestead.yaml
文件後,須要從新加載配置文件信息才能生效。javascript
➜ ~ cd Homestead ➜ Homestead git:(7924ab4) vagrant reload --provision
Hosts配置域名在mac的位置: /etc/hosts
php
192.168.10.10 digtime.app
digtime.appcss
cd ~/Homestead && vagrant up vagrant ssh cd ~/Code/digtime
npm install
執行全部未執行的遷移html
php artisan migrate
回滾上一次的遷移前端
vagrant@homestead:~/Code/digtime$ php artisan migrate:rollback
php artisan make:auth
Laravel 爲咱們默認建立的模型文件放置在 app
文件夾下,爲了更符合 MVC
模式的開發流程,本博文統一使用 app/Models
文件夾來放置全部的模型文件。如今讓咱們先來建立一個 app/Models
文件夾,並將 User.php
文件放置到其中。java
$ mkdir app/Models $ mv app/User.php app/Models/User.php
在執行完這一步的操做以後,咱們還須要執行下面這兩個操做:jquery
一、修改 User.php
文件,更改 namespace
爲咱們新建立的文件夾路徑:
app/Models/User.phpwebpack
<?php namespace App\Models; .
二、全局更改 App\User
爲 App\Models\User
,在 Atom中使用快捷鍵 shift + cmd(ctrl) + f
來進行全局搜索替換的操做。laravel
完成以後,點擊右下角的 Replace All
按鈕。git
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
有關Laravel5.4 的 webpack
使用,請看個人這篇博文:
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
http://editor.integ.me/ segmentfault 家的,解析庫也有:https://segmentfault.com/a/11...
https://laravel-china.org/top...
Markdown編輯器:https://simplemde.com/
這個編輯器看起來挺不錯,很簡潔,咱們能夠集成在咱們的項目中。
npm install simplemde --save
在resources/assets/js/bootsrap.js
中引入剛下載的資源包:
// 引入markdown編輯器 window.simplemde = require('simplemde');
使用命令編譯剛引入的資源,這樣才能夠編輯在 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: [""], 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>
咱們能夠給下邊的 laravel-admin後臺 集成該 Markdown
的編輯器。
Simplemde
是一個優秀簡潔的Markdown
編輯器,若是 laravel-admin
自帶的基於 ckeditor
的編輯器組件使用上有問題,能夠經過下面的步驟能夠集成它,並覆蓋掉ckeditor
:
先下載前端庫文件Simplemde, 解壓到目錄 public/packages/admin/simplemde
而後新建組件類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(); } }
而後註冊進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);
// 這樣就可使用咱們上邊自定義的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'); }); }
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);
找了一個很是簡潔的 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>
代碼塊是否是很簡潔清爽許多呢?
咱們能夠在項目中引入開源的管理後臺,這樣能夠大大的提升咱們的項目開發速度,這裏推薦兩個很是強大的開源管理後臺。
【擴展推薦】管理員後臺快速生成工具 Administrator "加強版" 分享
項目GitHub地址:summerblue/administrator
該後臺很是好用,由Laravel-China
團隊維護開發,十分鐘就能夠搭建起一個簡單的管理後臺:
該管理後臺很是強大,使用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'); }
爲了使咱們的文章詳情頁更利於瀏覽,像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>
DemoGist:corwien/markdown-side-menu-demo.html