Pre-required

  • Install docker
  • Install docker-compose

    1
    2
    
    curl -fsSL get.docker.com -o get-docker.sh
    sh get-docker.sh
    1
    2
    3
    
    sudo curl -L https://github.com/docker/compose/releases/download/1.22.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    docker-compose --version
    1
    
    sudo usermod -aG docker [your-user]

Install Laradock

1
2
cd ~
git clone https://github.com/LaraDock/laradock.git
1
2
cd laradock
cp env.example .env

.env一開始按照預設,之後熟了可以自行修改

Modify some config

Create ~/Project

1
mkdir -p ~/Project

vi ~/laradock/.env

1
APP_CODE_PATH_HOST=~/Project

~/laradock/nginx

1
2
cp ~/laradock/nginx/sites/laravel.conf.example ~/laradock/nginx/sites/laravel.conf
mv default.conf default.conf.old

Run docker

1
docker-compose up -d nginx mysql redis php-worker

接下來會跑一段時間安裝環境 雖然沒有指定-d workspace,但預設也會建立起來

Create laravel project in workspace

1
docker-compose exec workspace bash
1
2
3
composer create-project laravel/laravel --prefer-dist laravel

chmod 777 -R laravel/storage

Send Email Demo Code

vi .env

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=YOUR_MAIL_HOST
MAIL_PORT=YOUR_MAIL_PORT
MAIL_USERNAME=YOUR_MAIL_USERNAME
MAIL_PASSWORD=YOUR_MAIL_PASSWORD
MAIL_ENCRYPTION=ssl
MAIL_NAME="Laravel Demo Mail"
MAIL_FROM=${MAIL_USERNAME}

vi routes/api.php

1
Route::get('/demo/mail', "TestController@mail");

vi app/Http/Controller/TestController.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Mail;

class TestController extends Controller
{
    public function mail()
    {
        $this->dispatch(new \App\Jobs\SendReminderEmail("Hello World"));

        return "send demo email";
    }
}

create job for sending demo email

1
php artisan make:job SendReminderEmail

vi Jobs/SendReminderEmail.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
protected $content;

public function __construct(string $content)
{
    $this->content = $content;
}

public function handle(Mailer $mailer)
{
    
    $mailer->send(
        'emails.reminder', ['content' => $this->content], function ($m) {
            $m->from(env('MAIL_FROM'), env('MAIL_NAME'));
            $m->to("TARGET_EMAIL")->subject('Demo mail from Laravel');
        }
    );
}

vi resources/views/emails/reminder.blade.php

1
2
[Content]<br>
{!! $content !!}

Run Demo

1
curl http://127.0.0.1/api/demo/mail

執行後,laravel會在redis產生一個SendReminderEmail的job工作,接著背景工作php-worker就會處理寄信的動作

Restart docker-compose

1
2
3
docker-compose down

docker-compose up -d nginx mysql redis php-worker

如果Jobs, resource/views/emails, Controller, .env… 等相關的email有更新,記得一定要重新啟動php-worker套用更新後的程式

Reference