天天看點

Laravel-進階篇:Composer、Laravel、Artisan、Auth、檔案上傳、郵件、緩存、錯誤&日志、隊列Laravel-進階篇

Laravel -進階篇

第1章 Composer 快速入門

1 Composer簡介

包管理器

Java: Maven
NodeJS: NPM
Objective-C: CocoaPods
PHP: PEAR      

PEAR缺點

依賴處理容易出問題

配置非常複雜

難用的指令行接口

Composer

Composer是PHP的一個依賴(dependency)管理工具,不是包管理器

涉及packages 和 libraries

在項目中聲明所依賴的外部工具庫,Composer會自動安裝這些工具庫及依賴的庫檔案

Composer官網

https://getcomposer.org/

Composer中文網

https://www.phpcomposer.com/

2 安裝Composer

下載下傳 composer.phar

https://getcomposer.org/download/

局部安裝

php composer.phar      

全局安裝

sudo mv composer.phar /usr/local/bin/composer
sudo chmod -R 755 /usr/local/bin/composer      

3 Composer中國全量鏡像

https://pkg.phpcomposer.com/

使用阿裡鏡像

https://mirrors.aliyun.com/composer

啟用鏡像服務

1、單個項目配置

echo '{}' > composer.json
composer config repo.packagist composer https://mirrors.aliyun.com/composer      

2、系統全局配置

# 檢視目前鏡像位址
composer config -g repo.packagist.org

# 配置鏡像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer

# 解除鏡像
composer config -g --unset repos.packagist      

4 使用Composer

搜尋 search

展示 show

申明依賴 require

安裝 install

更新 update

# 初始化
$ composer init

{
    "name": "demo/demo",
    "description": "demo",
    "type": "library",
    "authors": [
        {
            "name": "pengshiyu",
            "email": "[email protected]"
        }
    ],
    "require": {}
}

# 搜尋
$ composer search monolog

# 顯示資訊
$ composer show --all monolog/monolog

# 配置依賴并安裝
"require": {
    "monolog/monolog": "2.0.1"
}

$ composer install

# 通過require安裝
$ composer require symfony/http-foundation

"require": {
        "monolog/monolog": "1.25.2",
        "symfony/http-foundation": "^4.4"
    }

# 更新依賴
"require": {
        "symfony/http-foundation": "^4.4"
    }
$ composer update
      

第2章 PHP架構安裝之Laravel

https://laravel.com/docs/5.8

Composer 安裝Laravel的兩種方式

1、通過Composer Create-Project安裝

# 安裝最新
composer create-project --prefer-dist laravel/laravel [别名] 

# 安裝指定版本
composer create-project --prefer-dist laravel/laravel blog "5.8.*"      

2、Laravel安裝器

安裝最新版本

composer global require "laravel/installer"      

添加環境變量

$ vim ~/.bash_profile

# composer
export PATH=$PATH:$HOME/.composer/vendor/bin      
laravel new blog      

Artisan是Laravel自帶指令行工具

Symfony Console元件驅動

# 檢視指令 
php artisan 

# 或者 
php artisan list

# 檢視幫助
php artisan help migrate

# 建立控制器
php artisan make:controller StudentController

# 建立模型
php artisan make:model Student

# 建立中間件
php artisan make:middleware Activity      

實作了登入注冊功能

2、Laravel中的資料遷移

# 建立資料表遷移檔案
php artisan make:migration create_students_table

# --table 指定資料表名
# --create 遷移檔案是否要建立新的資料表
# eg:
php artisan make:migration create_students_table --create=students

# 生成模型時同時生成遷移檔案
php artisan make:model Student -m
      

編輯遷移檔案

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('age')->unsigned()->default(0);
            $table->integer('sex')->unsigned()->default(0);
            $table->integer('created_at')->default(0);
            $table->integer('updated_at')->default(0);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}
      

用遷移檔案建立表

php artisan migrate      

檢視表結構

show create table students

CREATE TABLE `students` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `age` int(10) unsigned NOT NULL DEFAULT '0',
  `sex` int(10) unsigned NOT NULL DEFAULT '0',
  `created_at` int(11) NOT NULL DEFAULT '0',
  `updated_at` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci      

3、Laravel中的資料填充

建立填充檔案

php artisan make:seeder StudentTableSeeder      

編輯填充檔案

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class StudentTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
        DB::table('students')->insert([
            ['name'=> 'Tom', 'age'=> 23],
            ['name'=> 'Jack', 'age'=> 24],
            ['name'=> 'Greed', 'age'=> 25],
        ]);
    }
}
      

執行單個填充檔案

php artisan db:seed --class=StudentTableSeeder      

批量執行填充檔案

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(StudentTableSeeder::class);
    }
}
      

執行批量填充

php artisan db:seed      

第5章 Laravel架構常用功能

檔案上傳、郵件、緩存、錯誤&日志、隊列

1、Laravel中的檔案上傳

Laravel檔案系統基于Frank de Jonge Flysystem擴充包

配置檔案

config/filesystems.php

return [
    'disks' => [
        'uploads' => [
            'driver' => 'local',
            'root' => public_path('uploads'),
        ],
    ],

];
      

模闆檔案

resources/views/upload.blade.php

<form action="" method="post" enctype="multipart/form-data">
    {{csrf_field()}}
    <input type="file" name="file">
    <input type="submit">
</form>      

控制器

app/Http/Controllers/FileController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    //
    public function upload(Request $request)
    {
        if ($request->isMethod('POST')) {
            $file = $request->file('file');
            if ($file->isValid()) {
                // 原檔案名
                $originalName = $file->getClientOriginalName();

                // 擴充名
                $ext = $file->getClientOriginalExtension();

                // 類型
                $type = $file->getMimeType();

                // 臨時絕對路徑
                $realPath = $file->getRealPath();
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;

                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));

                var_dump($bool);
            }
        } else {
            return view('upload');
        }
    }
}
      

生成的檔案路徑

public/uploads/2019-12-01-12-51-38-5de3b75a97f0e.png

2、Laravel中的郵件發送

Laravel 郵件功能基于SwiftMailer 函數庫

配置

config/mail.php

MAIL_DRIVER=smtp
MAIL_HOST=smtp.163.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=ssl
[email protected]
MAIL_FROM_NAME=username      

163郵箱要求from和username必須一緻

發送

1、Mail::raw()

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Mail;

class MailController extends Controller
{
    public function mail()
    {
        Mail::raw('郵件内容', function ($message){
           $message->subject('郵件主題');
           $message->to('[email protected]');
        });
    }
}
      

2、Mail::send()

郵件模闆

resources/views/mail.blade.php

<h1>{{$name}}</h1>      
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Mail;

class MailController extends Controller
{
    public function mail()
    {
        Mail::send('mail', ['name'=> 'Laravel'], function ($message){
           $message->subject('郵件主題');
           $message->to('[email protected]');
        });
    }
}
      

3、Laravel中的緩存使用

Laravel支援常見的後端緩存系統

File、Memcached、Redis

use Illuminate\Support\Facades\Cache;

static bool has(string $key)

static bool put(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl)

# key存在不添加,不存在添加
static bool add(string $key, $value, \DateTimeInterface|\DateInterval|int $ttl)

static mixed get(string $key, mixed $default = null)

// 取出并删除
static mixed pull(string $key, mixed $default = null)

static bool forever(string $key, $value)
static bool forget(string $key)      

配置預設類型為file

config/cache.php

4、Laravel中的錯誤與日志

1、DEBUG模式

config/app.php

// 本地開發 
APP_DEBUG=true

// 線上環境 
APP_DEBUG=false      

2、HTTP異常

自定義異常模闆

resources/views/errors/500.blade.php

500      

使用

abort(500);      

Laravel預設提供404未找到等異常頁面

3、日志

Laravel基于Monolog提供日志模式:

single,

daily, 每天生成一個日志檔案

syslog,

errorlog

七個錯誤級别

debug

info

notice

warning

error

critical

alert

日志路徑

storage/logs

使用示例

use Illuminate\Support\Facades\Log;

LOG::info('info 級别的日志');
      

5、Laravel中的隊列應用

隊列服務允許推遲耗時任務執行,提高web請求速度

比如發送郵件執行

主要步驟

遷移隊列需要的資料表

編寫任務類

推送任務到隊列

運作隊裡監聽器

處理失敗任務

config/queue.php

QUEUE_CONNECTION=database      

建立隊列資料表

php artisan queue:table

php artisan migrate

php artisan make:job SendEmail
      

app/Jobs/SendEmail.php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $email;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        $this->email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::raw('郵件内容', function ($message){
            $message->subject('郵件主題 測試');
            $message->to($this->email);
        });
    }
}
      
dispatch(new SendEmail('[email protected]'));      

執行任務

php artisan queue:listen

php artisan queue:listen --tries=3      

遷移失敗任務表

php artisan queue:failed-table

php artisan migrate      

失敗任務操作

# 檢視失敗隊列
php artisan queue:failed

# 重試一次,指定id
php artisan queue:retry 1

# 重試所有
php artisan queue:retry all

# 删除失敗任務,指定id
php artisan queue:forget 1

# 清空失敗任務
php artisan queue:flush      

報錯:Class ‘Predis\Client’ not found

composer require predis/predis ^1.1      

總結

1、安裝和使用composer

2、composer安裝laravel

3、artisan控制台

4、auth使用者驗證

5、資料遷移,資料填充

6、檔案、郵件、緩存、隊列