teracrafts/huefy-laravel 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

teracrafts/huefy-laravel

Composer 安装命令:

composer require teracrafts/huefy-laravel

包简介

Laravel package for Huefy - App Mail Templates with seamless integration, service providers, and artisan commands

README 文档

README

The official Laravel package for Huefy - App Mail Templates. Provides seamless integration with Laravel's mail and notification systems, along with artisan commands and service providers for easy template-based email management.

Installation

Install the package via Composer:

composer require teracrafts/huefy-sdk-laravel

Laravel Auto-Discovery

The package uses Laravel's auto-discovery feature, so the service provider and facade are registered automatically.

Manual Registration (if needed)

If auto-discovery is disabled, add the service provider to your config/app.php:

'providers' => [
    // ...
    TeraCrafts\HuefyLaravel\HuefyServiceProvider::class,
],

'aliases' => [
    // ...
    'Huefy' => TeraCrafts\HuefyLaravel\Facades\Huefy::class,
],

Publish Configuration

Publish the configuration file:

php artisan vendor:publish --tag=huefy-config

Configuration

Add your Huefy API key to your .env file:

HUEFY_API_KEY=your-huefy-api-key
HUEFY_DEFAULT_PROVIDER=ses
HUEFY_TIMEOUT=30
HUEFY_RETRY_ATTEMPTS=3

Basic Usage

Using the Facade

use TeraCrafts\HuefyLaravel\Facades\Huefy;

// Send a single email
$response = Huefy::sendEmail('welcome-email', [
    'name' => 'John Doe',
    'company' => 'Acme Corp'
], 'john@example.com');

// Send with specific provider
$response = Huefy::sendEmail('newsletter', [
    'name' => 'Jane Smith',
    'unsubscribe_url' => 'https://example.com/unsubscribe'
], 'jane@example.com', 'sendgrid');

// Send bulk emails
$emails = [
    [
        'template_key' => 'welcome-email',
        'data' => ['name' => 'John'],
        'recipient' => 'john@example.com'
    ],
    [
        'template_key' => 'welcome-email', 
        'data' => ['name' => 'Jane'],
        'recipient' => 'jane@example.com',
        'provider' => 'mailgun'
    ]
];

$results = Huefy::sendBulkEmails($emails);

Using Dependency Injection

use TeraCrafts\HuefyLaravel\HuefyClient;

class EmailService
{
    public function __construct(private HuefyClient $huefy)
    {
    }

    public function sendWelcomeEmail(User $user): void
    {
        $this->huefy->sendEmail('welcome-email', [
            'name' => $user->name,
            'email' => $user->email,
            'login_url' => route('login')
        ], $user->email);
    }
}

Laravel Mail Integration

Configure Huefy as a mail driver in config/mail.php:

'mailers' => [
    'huefy' => [
        'transport' => 'huefy',
        'template_key' => env('HUEFY_DEFAULT_TEMPLATE_KEY'),
        'provider' => env('HUEFY_DEFAULT_PROVIDER', 'ses'),
    ],
],

Using with Mailables

use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;

class WelcomeMail extends Mailable
{
    public function __construct(
        public User $user
    ) {}

    public function build()
    {
        return $this->view('emails.welcome')
                    ->with([
                        'name' => $this->user->name,
                        'login_url' => route('login')
                    ])
                    ->subject('Welcome to our platform!');
    }

    public function envelope()
    {
        return new Envelope(
            subject: 'Welcome!',
            using: [
                fn (Message $message) => $message
                    ->getHeaders()
                    ->addTextHeader('X-Template-Key', 'welcome-email')
                    ->addTextHeader('X-Template-Data', json_encode([
                        'name' => $this->user->name,
                        'login_url' => route('login')
                    ]))
                    ->addTextHeader('X-Email-Provider', 'sendgrid')
            ]
        );
    }
}

// Send the email
Mail::to('user@example.com')->send(new WelcomeMail($user));

Laravel Notification Integration

Creating a Huefy Notification

use Illuminate\Notifications\Notification;
use TeraCrafts\HuefyLaravel\Notifications\HuefyChannel;
use TeraCrafts\HuefyLaravel\Notifications\HuefyMessage;

class WelcomeNotification extends Notification
{
    public function __construct(
        private User $user
    ) {}

    public function via($notifiable): array
    {
        return [HuefyChannel::class];
    }

    public function toHuefy($notifiable): HuefyMessage
    {
        return HuefyMessage::create('welcome-email')
            ->data([
                'name' => $this->user->name,
                'email' => $this->user->email,
                'activation_url' => route('activation', $this->user->id)
            ])
            ->provider('sendgrid');
    }
}

// Send the notification
$user->notify(new WelcomeNotification($user));

Using Route Notification

// In your User model
public function routeNotificationForHuefy()
{
    return $this->email;
}

// Or return an array for more complex routing
public function routeNotificationForHuefy()
{
    return [
        'email' => $this->email,
        'name' => $this->name
    ];
}

Artisan Commands

The package provides several artisan commands for managing emails:

Health Check

Check the Huefy API health status:

php artisan huefy:health

Send Email

Send an email using a template:

# Basic usage
php artisan huefy:send welcome-email user@example.com

# With inline data
php artisan huefy:send welcome-email user@example.com --data='{"name":"John","company":"Acme"}'

# With data from file
php artisan huefy:send welcome-email user@example.com --file=data.json

# With specific provider
php artisan huefy:send newsletter user@example.com --provider=sendgrid --data='{"name":"Jane"}'

Validate Template

Validate a template with test data:

# Interactive validation
php artisan huefy:validate welcome-email

# With inline data
php artisan huefy:validate welcome-email --data='{"name":"Test User"}'

# With data from file
php artisan huefy:validate welcome-email --file=test-data.json

List Providers

List available email providers:

php artisan huefy:providers

Advanced Usage

Custom Mail Transport

Create a custom mailable that uses Huefy transport:

use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;

class CustomHuefyMail extends Mailable
{
    public function __construct(
        private string $templateKey,
        private array $templateData,
        private ?string $provider = null
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Custom Huefy Email',
        );
    }

    public function content(): Content
    {
        return new Content(
            text: 'emails.empty', // Dummy view since we're using templates
        );
    }

    public function headers(): Headers
    {
        return new Headers(
            text: [
                'X-Template-Key' => $this->templateKey,
                'X-Template-Data' => json_encode($this->templateData),
                'X-Email-Provider' => $this->provider ?: config('huefy.default_provider'),
            ],
        );
    }
}

Bulk Email Processing

use TeraCrafts\HuefyLaravel\Facades\Huefy;

class NewsletterService
{
    public function sendNewsletter(Collection $subscribers, string $templateKey): array
    {
        $emails = $subscribers->map(function ($subscriber) use ($templateKey) {
            return [
                'template_key' => $templateKey,
                'data' => [
                    'name' => $subscriber->name,
                    'preferences_url' => route('preferences', $subscriber->id),
                    'unsubscribe_url' => route('unsubscribe', $subscriber->token),
                ],
                'recipient' => $subscriber->email,
                'provider' => $subscriber->preferred_provider ?? 'ses',
            ];
        })->toArray();

        return Huefy::sendBulkEmails($emails);
    }
}

Error Handling

use TeraCrafts\HuefyLaravel\Exceptions\HuefyException;
use TeraCrafts\HuefyLaravel\Exceptions\TemplateNotFoundException;
use TeraCrafts\HuefyLaravel\Exceptions\ValidationException;
use TeraCrafts\HuefyLaravel\Facades\Huefy;

try {
    Huefy::sendEmail('welcome-email', $data, $email);
} catch (TemplateNotFoundException $e) {
    Log::error('Template not found', [
        'template' => $e->getTemplateKey(),
        'message' => $e->getMessage()
    ]);
} catch (ValidationException $e) {
    Log::error('Validation failed', [
        'errors' => $e->getErrors(),
        'message' => $e->getMessage()
    ]);
} catch (HuefyException $e) {
    Log::error('Huefy API error', [
        'code' => $e->getCode(),
        'message' => $e->getMessage(),
        'context' => $e->getContext()
    ]);
}

Queue Integration

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use TeraCrafts\HuefyLaravel\Facades\Huefy;

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

    public function __construct(
        private string $templateKey,
        private array $data,
        private string $recipient,
        private ?string $provider = null
    ) {}

    public function handle(): void
    {
        Huefy::sendEmail(
            $this->templateKey,
            $this->data,
            $this->recipient,
            $this->provider
        );
    }
}

// Dispatch the job
SendHuefyEmailJob::dispatch('welcome-email', $data, $email)->onQueue('emails');

Configuration Reference

The config/huefy.php file contains all configuration options:

return [
    // API Configuration
    'api_key' => env('HUEFY_API_KEY'),
    'timeout' => env('HUEFY_TIMEOUT', 30),
    'retry_attempts' => env('HUEFY_RETRY_ATTEMPTS', 3),
    'default_provider' => env('HUEFY_DEFAULT_PROVIDER', 'ses'),

    // Mail Integration
    'mail' => [
        'default_template_key' => env('HUEFY_DEFAULT_TEMPLATE_KEY'),
        'auto_extract_data' => env('HUEFY_AUTO_EXTRACT_DATA', true),
    ],

    // Notification Integration
    'notifications' => [
        'default_template_key' => env('HUEFY_NOTIFICATION_TEMPLATE_KEY'),
        'include_notification_data' => env('HUEFY_INCLUDE_NOTIFICATION_DATA', true),
    ],

    // Logging
    'logging' => [
        'log_successful_sends' => env('HUEFY_LOG_SUCCESS', false),
        'log_failed_sends' => env('HUEFY_LOG_FAILURES', true),
        'channel' => env('HUEFY_LOG_CHANNEL', 'default'),
    ],

    // Rate Limiting
    'rate_limiting' => [
        'enabled' => env('HUEFY_RATE_LIMITING_ENABLED', true),
        'requests_per_minute' => env('HUEFY_REQUESTS_PER_MINUTE', 60),
    ],
];

Testing

use TeraCrafts\HuefyLaravel\Facades\Huefy;

// Mock the Huefy facade for testing
public function test_sends_welcome_email()
{
    Huefy::shouldReceive('sendEmail')
        ->once()
        ->with('welcome-email', ['name' => 'John'], 'john@example.com', null)
        ->andReturn(['message_id' => 'test-123', 'status' => 'sent']);

    $result = $this->emailService->sendWelcome('john@example.com', 'John');

    $this->assertTrue($result);
}

Requirements

  • PHP 8.1 or higher
  • Laravel 9.0, 10.0, or 11.0
  • Guzzle HTTP client 7.0+

License

This package is open-sourced software licensed under the MIT license.

Support

teracrafts/huefy-laravel 适用场景与选型建议

teracrafts/huefy-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 07 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「mail」 「mailchimp」 「api」 「email」 「notifications」 「templates」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 teracrafts/huefy-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 teracrafts/huefy-laravel 我们能提供哪些服务?
定制开发 / 二次开发

基于 teracrafts/huefy-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 23
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-07-03