Lim*_*nte 5 php code-organization laravel laravel-5 laravel-validation
我想知道我想在多个地方使用的自定义验证器的正确位置在哪里?
例如,我有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]);
});
Run Code Online (Sandbox Code Playgroud)
我应该在哪里按照Laravel-way的方式放置它?
绝对扩展服务提供者中的验证器.您可以使用现有的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]);
});
}
Run Code Online (Sandbox Code Playgroud)
将实际验证规则放在单独的类中并使用以下语法也是值得的:
$this->app['validator']->extend('min_image_size', 'MyCustomValidator@validateMinImageSize');
Run Code Online (Sandbox Code Playgroud)