[Catalyst] Best practice for database connections, where $c is not available?

Bill Moseley moseley at hank.org
Wed Dec 31 17:48:11 GMT 2008

On Wed, Dec 31, 2008 at 03:37:13PM +0000, Oliver Charles wrote:
> Hi,
> This has hit me a few times, and I've just encountered it again, so I
> thought it would be good to ask those wiser than I :)
> There have been a few times where I could do with querying the
> database (which I'd normally do through $c->model), but this is not
> available. For example, I've added the option for users to specify how
> to display dates on our website, through a variety of formats. I
> thought the best way to do this, would be using a Template Toolkit
> plugin:
>     [% USE user_date %]
>     The date is [% user_date.format(some_date) %].
> However, this plugin needs to access the user preferences model
> ($c->model('UserPreference')->date_format($user)).

Don't know about your plugin, but shouldn't you be able to get $c from
the template stash?  $stash = $context->stash.  Then use

But, I'm with Ash on this -- I only allow users to specify a timezone
(and language/locale).

So I set:

    $c->stash->{user_time} = $current_user
        ? sub { return shift->clone->set_time_zone( $current_user->timezone->name || 'UTC' ) }
        : sub { return shift };

And then use:

    [% user_time(item.start_time).strftime( '%x %X' ) %]

I leave the format in the template as it seems like a display issue
that template authors might want more control over w/o having to
update the application.

On another project I set up TT vmethods that defined a number of
formats and then in the template I would do:

    [% item.start_time.full_date %]
    [% item.start_time.time_with_zone %]

But, I'm not sold on that approach.

Bill Moseley
moseley at hank.org
Sent from my iMutt

More information about the Catalyst mailing list