[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [cgiapp] RFC: Data::FormValidator 4.0


On 7/2/05, Jason Purdy <suppressed> wrote:
> What I find amazing is the whole closure thing.  That was one of the
> things that was hanging me up - when writing customized constraint
> methods, it would have been nice to have access to some of the
> application data (database handles, mostly, if I recall correctly).
> 
> Thinking back -- let's say I wanted to constrain the email address by
> checking the database to see if it already exists or not:
> 
> sub _my_profile
> {
>    return
>    {
>      'constraints' =>
>      {
>        'email' => \&_check_email,
>      },
>    };
> }
> 
> sub _check_email
> {
>    my ( $email );
>    $email = shift;
>    # now here's my problem ... now I have to create a db handle
>    # when one already exists ... if I only had access to the cgiapp
>    # $self instance.
> }

You can do that with the current version as long as you use an
anonymous subroutine (hence a closure):

'constraints' => {
       'email' => sub { _check_email( $self->dbh, @_ ) },
},

sub _check_email {
    my $db = shift;
    my $email = shift;
    # yada yada yada
}


Since I use Class::DBI, I often have checks like this:

'constraints' => {
       'uname' => sub { ! MyApp::DB::Users->search( name => $_[0] )->first; }
},

That will do a search in the Users table to see if a user with that
name already exists.  That would only be used when creating a new
user.  When updating a user, there will obviously be an entry with
that name already.

You can do the reverse as well if you have a drop down list that is
populated by a table in the database, and you want to verify that the
answer you received in the form is actually valid:

'constraints' => {
       'group_id' => sub { MyApp::DB::Groups->search( id => $_[0] )->first; }
},

That tells me that the group_id does exist in the database.

Closures were probably the biggest sticking point for me when I was
learning perl.  It took me a long time to get my head around them. 
But they are a very powerful tool, and can bail you out of tricky
situations.

Although I haven't seen or read the book yet, from the sounds of it,
'Higher Order Perl' deals extensively with this stuff, and would be a
good buy.

Cheers,

Cees

---------------------------------------------------------------------
Web Archive:  http://www.mail-archive.com/suppressed/
              http://marc.theaimsgroup.com/?l=cgiapp&r=1&w=2
To unsubscribe, e-mail: suppressed
For additional commands, e-mail: suppressed


Mail converted by mhonarc 2.6.15
This archive provided courtesy of JSW4.NET, Internet Hosting Services for Small Business.