[Petal] Implementation question
Jean-Michel Hiver
jhiver@mkdoc.com
Wed, 21 Aug 2002 17:55:43 +0100
Hi William,
I'm going to make the following assumptions:
* all your records are hashrefs which come from some database
* you have a list of them to display
Let's say that the database table looks like this:
Raters (id, first_name, last_name, relation, phone, email)
You could bless each record into a package as is:
use MyApplication::Record::Rater;
my @records = complicated_query_somewhere_else();
bless $_, "MyApplication::Record::Rater" for (@records);
Your module could look like that:
package MyApplication::Record::Rater;
use strict;
use warnings;
use CGI;
use Carp;
sub is_current_id
{
my $self = shift;
my $cgi = CGI->new;
my $id = $cgi->param ('rater.id');
return unless (defined $id and $id and $id =~ /^\d+$/);
return $id == $self->{id};
}
1;
Then on top of your existing data, you have a method which you can call
from Petal, i.e.
<span petal:condition="true:record/is_current_id">
blah blah blah...
</span>
This trick can also be used when you have foreign keys in database
fields.
<fictious_scenario>
For example, let's imagine that you have a column called
'friend_id'. It references another 'rater' which is supposed to be a
friend of that person.
You could defined the following subroutine:
# give me the friend record for that person
sub friend
{
my $self = shift;
my $friend_id = $self->{friend_id};
my $sql = 'select * from rater where id = ?';
my $sth = $::DBH_CONNECTION->prepare_cached ($sql);
$sth->execute ($friend_id);
my $hash = $sth->fetchrow_hashref;
return unless (defined $hash);
bless $hash, "MyApplication::Record::Rater";
return $hash;
}
Then in your template, you could do:
<?petal:if name="true:rater/friend"?>
Your friend is:
$encode:rater/friend/first_name
$encode:rater/friend/last_name
<?petal:end?>
</fictious_scenario>
This system is quite poweful, I use it heavily all the time, and that's
why Petal supports invoking method on objects.
In other words, OO-Perl rulez :-)
Cheers,
--
IT'S TIME FOR A DIFFERENT KIND OF WEB
================================================================
Jean-Michel Hiver - Software Director
jhiver@mkdoc.com
+44 (0)114 255 8097
================================================================
VISIT HTTP://WWW.MKDOC.COM