modulate/artisan-interceptor

允许您为 artisan 命令添加选项、监听器和处理器

v1.0.0 2023-09-18 09:23 UTC

This package is auto-updated.

Last update: 2024-09-18 11:46:29 UTC


README

一个简单而优雅的方法来改变 Artisan 命令的全局行为

Latest Version on Packagist Scrutinizer Code Quality Code Coverage Build Status Total Downloads

功能

  • 为 artisan 添加新的全局选项,例如 --tenant=2 或 --module=my-module
  • 添加在运行 artisan 命令之前和/或之后执行的处理器
  • 添加条件处理器,只有当命令中给出指定的选项时才执行
  • 流畅构建器,用于向 artisan 添加输入选项

添加全局选项

一般来说,目前没有简单的方法向 artisan 命令添加新的全局选项。像 --env 或 --version 这样的选项是内置的,但 artisan 没有提供添加新选项的内置方式。这就是 artisan interceptor 的用武之地。

拦截器允许您向 artisan 添加新的全局选项,并添加您自己的自定义处理器来检测和处理这些选项。所有这些操作都是通过内置的 artisan 事件完成的,但为您提供了一种干净而优雅的方式添加和交互新选项。

安装

您可以通过 composer 安装此包

composer require modulate/artisan-interceptor

用法

添加全局选项

// Add a new optional option to artisan
ArtisanInterceptor::addOption(
    ArtisanInterceptor::optionBuilder()
        ->name('tenant')
        ->optional()
        ->get()
);

// Adding required options to the shell to handle things like authentication
ArtisanInterceptor::addOptions(
    ArtisanInterceptor::optionBuilder()
        ->name('user')
        ->required()
        ->get(),
    ArtisanInterceptor::optionBuilder()
        ->name('password')
        ->required()
        ->get()
);

添加监听器

<?php
use Modulate\Artisan\Interceptor\InterceptedCommand;

ArtisanInterceptor::before(function(InterceptedCommand $intercepted) {
    // Add a callback that runs before the command is run
    // but will only run if the given option is set
    $intercepted->getOutput()->writeln(sprintf(
        'Hello from %s tenantId: %d', 
        $intercepted->getCommand(),
        $intercepted->getInput()->getOption('tenant')
    ));
}, 'tenant')
->after(function(InterceptedCommand $intercepted) {
    // Add a callback that runs after the command is run
    // but will only run if the given option is set
    $intercepted->getOutput()->writeln(sprintf(
        'exitCode %d',
        $intercepted->getExitCode(),
    ));
}, 'tenant')
->after(function(InterceptedCommand $intercepted) {
    // You can also omit the option parameter to a before or after
    // callback to always run the callback
    $intercepted->getOutput()->writeln('This callback will always run after a command');
});

扩展拦截器

您对所有回调类型都有完全控制权。您甚至可以通过直接实现处理器合约来添加自己的自定义处理器

测试

vendor/bin/testbench package:test