5

我想知道我想在多个地方使用的自定义验证器的正确位置在哪里?

例如,我有min_image_size验证器:

Validator::extend('min_image_size', function($attribute, $value, $parameters) {
    $imageSize = getimagesize($value->getPathname());
    return ($imageSize[0] >= $parameters[0] && $imageSize[1] >= $parameters[1]);
});

我应该按照正确的 Laravel 方式将它放在哪里?

4

2 回答 2

7

绝对在Service Provider中扩展验证器。您可以使用现有的app/Providers/AppServiceProvider.php或创建另一个仅用于验证。

然后,在boot()方法中,添加:

public function boot(){
    $this->app['validator']->extend('min_image_size', function($attribute, $value, $parameters) {
        $imageSize = getimagesize($value->getPathname());
        return ($imageSize[0] >= $parameters[0] && $imageSize[1] >= $parameters[1]);
    });
}

将实际的验证规则放在一个单独的类中并使用以下语法也可能是值得的:

$this->app['validator']->extend('min_image_size', 'MyCustomValidator@validateMinImageSize');
于 2015-04-20T14:30:38.463 回答
-2

我想我将创建一个用于自定义验证的类,我可以在其中编写自定义规则并将其放入库文件夹或可能是中间件。

于 2015-04-20T08:56:45.537 回答