Catalyst
Contents
Creating a model
This generates an interface for Catalyst to a 'MyApp::Item' object and passes all methods through to the object. The example merely passes a 'datadir' attribute on the object that contains the full path to the "data" directory within the application root.
single instance per application
This can be useful if you need a counter that persists between requests for example
package MyApp::Model::Item;
use strict;
use warnings;
use base 'Catalyst::Model';
use MyApp::Item;
use Moose;
our $AUTOLOAD;
has 'Instance' => (
is => 'rw',
isa => 'MyApp::Item',
);
__PACKAGE__->config( class => 'MyApp::Item' );
sub COMPONENT {
my ($self, $app) = @_;
return MyApp::Item->new( datadir => $app->path_to("data") );
}
sub AUTOLOAD {
my $self = shift;
my $name = $AUTOLOAD;
$name =~ s/.*://;
$self->Instance->$name(@_);
}
1;
one instance per request
If you need one instance of $c->model('Item') per request, remove the COMPONENT method and add:
with 'Catalyst::Component::InstancePerContext';
sub build_per_context_instance {
my ($self, $c) = @_;
return MyApp::Item->new( datadir => $c->path_to("data") );
}
multiple instance per request
If you need a different instance of $c->model('Item') every time this is called (eg several items in a single request), start with the original example, remove the COMPONENT method and existing use base line and add:
use base 'Catalyst::Model::Factory';
sub ACCEPT_CONTEXT {
my ($self, $c, @args) = @_;
return MyApp::Item->new( datadir => $c->path_to("data") );
}
Rewriting all urls from uri_for()
Useful for when there's a proxy in front and it's rewriting things, or when SSL should be enabled and isn't.
Install Catalyst::TraitFor::Request::ProxyBase and add these two bits either side of the line: extends 'Catalyst';
use CatalystX::RoleApplicator;
...
__PACKAGE__->apply_request_class_roles(qw/
Catalyst::TraitFor::Request::ProxyBase
/);
In Apache config, add into the same sections as your ProxyPass lines:
<Location /preview> RequestHeader set X-Request-Base http://www.example.com/preview </Location>