Используйте Artisan для создания новой команды:
php artisan make:command SendEmailsCommand
Это создаст файл в app/Console/Commands/SendEmailsCommand.php
с базовой структурой.
Сгенерированный класс содержит:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendEmailsCommand extends Command
{
protected $signature = 'app:send-emails';
protected $description = 'Send emails to all users';
public function handle()
{
// Логика команды
}
}
После создания команду нужно зарегистрировать в app/Console/Kernel.php
:
protected $commands = [
Commands\SendEmailsCommand::class,
];
protected $signature = 'email:send {user}';
protected $signature = 'email:send {user?}';
protected $signature = 'email:send {--queue}';
protected $signature = 'email:send {user*}'.
protected $signature = 'email:send
{user : The ID of the user}
{--queue : Whether to queue the emails}
{--chunk=100 : Number of emails per chunk}';
В методе handle()
доступны методы для работы с вводом:
public function handle()
{
$userId = $this->argument('user');
$shouldQueue = $this->option('queue');
$chunkSize = $this->option('chunk');
$this->info("Sending emails to user $userId");
}
$this->info('Success message'); // Зеленый текст
$this->error('Error message'); // Красный текст
$this->line('Simple message'); // Обычный текст
$this->comment('Comment text'); // Желтый текст
$headers = ['Name', 'Email'];
$users = User::all(['name', 'email'])->toArray();
$this->table($headers, $users);
$users = User::all();
$this->output->progressStart($users->count());
foreach ($users as $user) {
// Отправка email
$this->output->progressAdvance();
}
$this->output->progressFinish();
$name = $this->ask('What is your name?');
$password = $this->secret('What is the password?');
if ($this->confirm('Do you wish to continue?')) {
//
}
$role = $this->choice(
'What role should the user have?',
['user', 'editor', 'admin'],
'user'
);
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class SendEmailsCommand extends Command
{
protected $signature = 'email:send
{--users=* : User IDs to send emails}
{--queue : Queue the emails}
{--chunk=100 : Number of emails per chunk}';
protected $description = 'Send newsletter emails to users';
public function handle()
{
$query = User::where('subscribed', true);
if ($ids = $this->option('users')) {
$query->whereIn('id', $ids);
}
$users = $query->cursor();
$total = $query->count();
$chunkSize = (int)$this->option('chunk');
$this->info("Starting to send $total emails...");
$users->chunk($chunkSize, function ($usersChunk) {
foreach ($usersChunk as $user) {
if ($this->option('queue')) {
Mail::to($user)->queue(new NewsletterMail());
} else {
Mail::to($user)->send(new NewsletterMail());
}
}
$this->info("Sent batch of " . count($usersChunk) . " emails");
});
$this->info('All emails sent successfully!');
}
}
Пример теста с PHPUnit:
public function test_send_emails_command()
{
$this->artisan('email:send', ['--users' => [1, 2]])
->expectsOutput('Starting to send 2 emails...')
->assertExitCode(0);
}
Консольные команды в Laravel:
make:command
Console/Kernel.php
Ключевые возможности:
Best Practices:
Производительность:
cursor()
Для production-окружения: