0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FuelPHPのEmailパッケージのドライバを追加してSendGridでメールを送信する

Posted at

FuelPHP の Email パッケージから呼び出して使えるドライバを実装しました。今回は SendGrid のドライバを実装しましたが、他にも応用できると思います。

やりたいこと

  • Email パッケージを使用して mail() 関数でメールを送信している処理を SendGrid に置き換えたい。
  • 既存の Email パッケージの関数を呼び出している処理をできるだけ流用したい。
  • できるだけきれいに拡張したい。

環境

  • FuelPHP 1.8.2

Email ドライバクラスの作成

fuel/app/classes/email/driver ディレクトリ以下に Email\Email_Driver クラスを継承する Email_Driver_<ドライバ名> クラスを作成します。
Email パッケージのソースコードを参考にして、他のドライバと同様の命名規則となるディレクトリ構成とクラス名にします。

fuel/app/classes/email/driver/sendgrid.php
<?php
class Email_Driver_Sendgrid extends Email\Email_Driver
{

}

Email パッケージの設定ファイルで、新たに作成したドライバを指定します。Mailgun ドライバに倣って、API キー等のドライバ固有の設定も併せて記載します。

fuel/app/config/email.php
<?php
return [
    'defaults' => [
        'driver' => 'sendgrid',
        'key' => '<YOUR API KEY>',
    ],
];

これで新たに作成したドライバが呼び出されるようになりました。あとは必要な関数を実装していきます。継承元クラスのうち、必要な public 関数を読み進めて、適宜オーバーライドします。

fuel/app/classes/email/driver/sendgrid.php
<?php
class Email_Driver_Sendgrid extends Email\Email_Driver
{
    protected function _send()
    {
        // Email\Email_Driver::_send() をオーバーライドする

        // メールの送信処理を実装する

        // ドライバがメール送信に失敗した際に投げるための例外が用意されているので、
        // 失敗したら投げる 
        throw new EmailSendingFailedException;
    }

    public function cc()
    {
        // ドライバで対応しない関数が呼び出されたら例外を投げるなどする
        throw new LogicException;
    }
}

参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?