[Catalyst] Search example in any docs?
Tomas Doran
bobtfish at bobtfish.net
Tue Sep 23 23:41:51 BST 2008
On 23 Sep 2008, at 21:21, Dr. Jennifer Nussbaum wrote:
> i have
> code that looks like
>
> if ( $c->req->params->{title} ) {
> my $title = "%" . $c->req->params->{title} . "%";
> push (@$query, { title => { like => $title } });
> }
>
> # exact match here
> if ( $c->req->params->{author} ) {
> my $performer = $c->req->params->{author};
> push (@$query, { author => { '=' => $author} });
> }
>
> etc., which just looks messy.
It's called refactoring - pull the common bits out and put them in a
base class for your controllers.
package MyApp::Controller;
use strict;
sub query_like {
my ($self, $c, $name) = @_;
return $self->query($c, $name, 'like', '%' . $c->req->param
($name) . '%');
}
sub query_eq {
my ($self, $c, $name) = @_;
return $self->query($c, $name, '=', $c->req->param($name));
}
sub _query {
my ($self, $c, $name, $operator, $val) = @_;
if ($c->req->param($name)) {
push @{$c->stash->{query}}, { $name => { $operator => $val } };
}
};
package MyApp::Controller::Search;
sub foo : Local {
my ($self, $c) = @_;
$self->query_like($c, 'title');
$self->query_eq($c, 'author');
}
Cheers
t0m
More information about the Catalyst
mailing list