[Catalyst] Model/Controller logic separation - best practices?

Zbigniew Lukasiak zzbbyy at gmail.com
Sat Mar 8 20:24:21 GMT 2008


On Tue, Mar 4, 2008 at 8:35 PM, Ian Sillitoe <catalyst at sillit.com> wrote:
> Hopefully there is a quick and obvious answer to the following - if so,
> apologies for the length of this email. Apologies in advance also if this is
> considered off-topic and/or covered in previous threads - I have trawled
> around for a while (and recently got Jonathan's book !) but all my solutions
> seem a bit like hacks and I'm hoping for a "Best Practice".
>
> My problem: given a row from table A, I would like to be able to return
> related entries from table B ideally from within a template (unless this is
> committing some kind of MVC heresy), I was thinking something like the
> following:
>
> Controller/TableA.pm:
> $c->{stash}->{row_a} = $c->model('MyDBIC::TableA')->find('id');
> $c->{stash}->{template} = 'view_a.tt2';
> $c->forward('Catalyst::View::TT');
>
> /root/src/view_a.tt2:
> [% rows_b = row_a.get_related_rows( optional => param ) %]
> [% FOREACH row_b = rows_b %]
>   [% DisplayRow(row_b) %]
> [% END %]
>
> However, there is a reasonable amount of logic required to get the related
> rows - the relationship between A and B is too complicated to encapsulate in
> a static "has_many" (especially with the optional params) so I can't use
> "row_a.search_related()". Assuming this is the case (rather than my DBIC
> incompetence):
>
> 1) where is the best place to put this logic? (Controller::ModelA.pm,
> DBIC::ModelA.pm, ResultSet::ModelA.pm??)
>
> 2) following from 1) what is the best way of accessing this logic from the
> template?


I would create an additional method in MyDBIC::TableA and then call it
in the template like:

[% rows_b = row_a.the_new_method( optional => param ) %]

If you needed to find the rows from the TableB independently from any
row in TableA you'd need to add that method to the TableB::ResultSet
class (or whatever name you'd use for it).  And then you could use it
like:
[% rows_b = b_rs.the_new_method( params ) %]

Cheers,
Zbigniew Lukasiak
http://perlalchemy.blogspot.com/



More information about the Catalyst mailing list