Jun
27
Yesterday we built our first page. Because we had to set up some
database mappings it may have seemed more complicated that it actually
was. If we wanted to add another page today that viewed a CD in a
different way, all we would have to do is add another lined to the
config_info in Site.pm:
sub config_info {qq{
/view/cd gets MDB::CD
/show/cd gets MDB::CD
}}
And now we just create another template in page/show/cd.tt.
Today we’ll build another similar page, for artist details.
In the database schema we had yesterday, we assumed that “artist” was
a field in the CD table. In reality this would usually be a foreign key
to an artist table, with, say, ‘artistid’ and ‘name’ columns. So let’s
migrate our system to that.
First, we create the MDB::Artist class, telling it what table the data
lives in, and setting up the has many relationship back to the CDs
by this artist.
package MDB::Artist;
use base 'MDB::DBI';
__PACKAGE__->set_up_table('artist');
__PACKAGE__->has_many(cds => MDB::CD => 'artist');
1;
Then we let the CD class know that its ‘artist’ column doesn’t contain
the artist name, but rather a pointer to the artist table:
package MDB::CD;
use base 'MDB::DBI';
__PACKAGE__->set_up_table('cd');
__PACKAGE__->has_many(tracks => MDB::Track => 'cd');
__PACKAGE__->hasa(MDB::Artist => 'artist');
1;
Now, any time we ask a cd for its artist we’ll get back an MDB::Artist
object instead of a plain string,
So, in our template, where we previously had
<h2>[% cd.artist %]</h2>
we now need
<h2>[% cd.artist.name %]</h2>
And now we can build our artist page. Again it’s very simple. We just
add it to our config_info:
sub config_info {qq{
/view/cd gets MDB::CD
/show/cd gets MDB::CD
/show/artist gets MDB::Artist
}}
And now we can create our artist template, page/show/artist.tt:
[% META browser_title = "Artist details" %]
<h1>[% artist.name %]</h1>
<p>CDs:
<ul>
[% FOREACH cd = artist.cds.sort('year') %]
<li>
<a href="/show/cd/[% cd.id %]">[% cd.title %]</a>
</li>
[% END %]
</ul>
</p>
And of course we should really go back to our CD template and link the
artist name to their own page:
<h2>
<a href="/show/artist/[% cd.artist.id %]">[% cd.artist.name %]</a>
</h2>
And now we have a simple browsing mechanism from a CD to its artist to
all that artist’s CDs.