从 Laracasts\Validation 类 中静态检索规则

Statically retrieving rules out of Laracasts\Validation classes

我有以下表单验证class:

class EditItemsForm extends Laracasts\Validation\FormValidator
{
    protected $rules = [
        'name' => 'required|alpha'
    ];
}

我需要使用 $rules 中的值来填充 Former::withRules(),这样它就可以做到这一点。

我可以尝试添加一个静态 getRules 方法,这样我就可以 Former::withRules(EditItemsForm::getRules()) 来获取受保护的值,但这需要创建一个 EditItemsForm 的新实例,父 FromValidator 需要 Laracasts\Validation\FactoryInterface 作为构造函数的第一个参数。

示例:

public static function getRules()
{
    return with(new self(null))->rules;
}

叫我被宠坏了,但我以前从来没有遇到过这种情况。所以习惯于 Laravel 在输入值传递给控制器​​时在后台进行神奇的依赖注入。

在这种情况下如何获得 $rules 的值而不必拥有 FactoryInterface 的实例,或者我如何动态创建该实例以将其传递给 getRules

您是否尝试过 Laravel 的 IoC container 来实例化 EditItemsForm class。这将为您解决依赖关系。

App::make('EditItemsForm');

引自 Laravel 文档

The IoC container is powerful enough to resolve classes without any configuration at all in many scenarios. For example:

class FooBar {

   public function __construct(Baz $baz)
   {
      $this->baz = $baz;
   }

}

$fooBar = App::make('FooBar');