larapack/command-validation

为Artisan命令启用一种方法,以验证类似于`ask`的方法的输出。

v1.0.0 2015-11-27 13:53 UTC

This package is auto-updated.

Last update: 2024-09-06 08:55:00 UTC


README

为Artisan命令启用一种方法,以验证类似于ask的方法的输出。

安装

使用composer安装 composer require "larapack/command-validation 1.*"

用法

首先将特质Validateable添加到您的Artisan命令中。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Larapack\CommandValidation\Validateable;

class ExampleCommand extends Command
{
  use Validateable;
  
  // ...
}

然后使用validate-方法

  public function fire()
  {
    // We want to get the age from the user, but we would like to validate it.
    // So we use the validate method.
    $age = $this->validate(function() {
      // Here we ask the question we want and return the output
      // Any method returning a value from the command line input can be used here.
      return $this->ask('What is your age?', null);
    }, function($value) {
      // Here we validate the value
      // If the value is NOT valid, we should return a error message.
      // If the value is valid, we don't need to return anything.
      // NOTE: Returning true will also be valid.
      if (!is_numeric($value)) return "Age [{$value}] is not numeric.";
    });
    
    // Once we are here you will have the validage age
    $this->info("So you are {$age} years old.");
  }

它看起来像这样

Command Line Example