我想重写 Illuminate\Validation\Validator
类中的方法 (isValidatable
)。我通过创建一个扩展 Validator 的类(在 Illuminate 外部)来完成此操作,并且仅重写 isValidatable
方法。
我认为这会起作用,但我不确定如何为 Validator 类(或者实际上是 CustomLaravelValidator
类)创建服务提供者。我之前已经创建过服务提供者,但是 Validator 服务提供者(Illuminate\Validation\ValidationServiceProvider
)内部似乎发生了很多事情。因此,我不知道此类的自定义服务提供者应该是什么样子。
这是我的 CustomLaravelValidator 类:
<?php namespace API\Extensions\Core;
use Illuminate\Validation\Validator;
class CustomLaravelValidator extends Validator {
/**
* Determine if the attribute is validatable.
*
* @param string $rule
* @param string $attribute
* @param mixed $value
* @return bool
*/
protected function isValidatable($rule, $attribute, $value)
{
// Validate integers on empty strings as well
if($rule == 'IntStrict')
{
return true;
}
return $this->presentOrRuleIsImplicit($rule, $attribute, $value) &&
$this->passesOptionalCheck($attribute);
}
}
这是 Laravel 的默认 ValidationServiceProvider:
<?php namespace Illuminate\Validation;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerPresenceVerifier();
$this->app->bindShared('validator', function($app)
{
$validator = new Factory($app['translator'], $app);
// The validation presence verifier is responsible for determining the existence
// of values in a given data collection, typically a relational database or
// other persistent data stores. And it is used to check for uniqueness.
if (isset($app['validation.presence']))
{
$validator->setPresenceVerifier($app['validation.presence']);
}
return $validator;
});
}
/**
* Register the database presence verifier.
*
* @return void
*/
protected function registerPresenceVerifier()
{
$this->app->bindShared('validation.presence', function($app)
{
return new DatabasePresenceVerifier($app['db']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('validator', 'validation.presence');
}
}
谁能告诉我我的定制服务提供商应该是什么样子?
最佳答案
您的服务提供商不需要模仿 native 验证器服务提供商。您只需使用验证器工厂上的 resolver
方法注册自定义验证器即可。
use API\Extensions\Core\CustomLaravelValidator;
class CustomValidationServiceProvider extends ServiceProvider {
public function boot()
{
$this->app['validator']
->resolver(function($translator, $data, $rules, $messages)
{
return new CustomLaravelValidator(
$translator,
$data,
$rules,
$messages
);
});
}
}
就是这样...
关于php - Laravel 验证器的自定义服务提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544748/