PrePAN

Sign in to PrePAN

Data::Validator::Manager instance manager for Data::Validator

Good

Synopsis

use Data::Validator::Manager;

my $v = Data::Validator::Manager->new;
$v->add_rule(hoge => +{
      foo => 'Str',
      bar => +{ isa => 'Str', default => 'baz' },
})->with(qw/Method/);

sub hoge {
    my($self, $args) = $v->validate(hoge => @_);

    # logic...
}

Description

This module is instance manager for Data::Validator. This can be used to standardize as name the validation rules.

This module is required in order to reduce unnecessary maintenance costs by utilizing a common validation rules.

example:

package Example::Model;
use strict;
use warnings;
use utf8;

sub get_with_cache {
    state $rule = Data::Validator->new(
        key => 'Str'
    )->with(qw/Method/);
    my($self, $args) = $rule->validate(@_);

    my $val = $self->cache->get($args->{key});
    return $val if defined $val;

    $val = $self->get($args);
    $self->cache->set($args->{key} => $val);

    return $val;
}

sub get {
    state $rule = Data::Validator->new(
        key => 'Str'
    )->with(qw/Method/);
    my($self, $args) = $rule->validate(@_);

    return $self->backend->get($args->{key});
}

sub delete_cache {
    state $rule = Data::Validator->new(
        key => 'Str'
    )->with(qw/Method/);
    my($self, $args) = $rule->validate(@_);

    return $self->cache->delete($args->{key});
}

1;

this methods use same validation rule. but, rule is defined each. This is a waste of memory space. If this validation rule changed, we must change each validation rule. Data::Validator::Manager can standardize the validation rules.

example Data::Validator::Manager::Declare :

package Example::Validator;
use strict;
use warnings;
use utf8;

use Data::Validator::Manager::Declare;

rule model_get => +{
    key => 'Str'
} => with(qw/Method/);

1;

use Example::Validator;

package Example::Model;
use strict;
use warnings;
use utf8;

use Example::Validator qw/validate/;

sub get_with_cache {
    my($self, $args) = validate(model_get => @_);

    my $val = $self->cache->get($args->{key});
    return $val if defined $val;

    $val = $self->get($args);
    $self->cache->set($args->{key} => $val);

    return $val;
}

sub get {
    my($self, $args) = validate(model_get => @_);

    return $self->backend->get($args->{key});
}

sub delete_cache {
    my($self, $args) = validate(model_get => @_);

    return $self->cache->delete($args->{key});
}

1;

Comments

再利用するにはいいけど、あとからどういうvalidation ruleを適用しているのかみたいときにValidatorみないといけないのが面倒かなと思いました。

Please sign up to post a review.