[Catalyst] How to avoid repeating methods in controllers ?
Hernan Lopes
hernanlopes at gmail.com
Sun Jul 21 16:30:49 GMT 2013
you might want something like this, where one class defines common
attributes, and other classes extend it, for example
package CommonAttributes;
use Moose;
has name => (
is => 'rw',
);
sub jump {
my ( $self, $c ) = @_;
warn "JUMP";
}
1;
package ControllerOne;
use Moose;
extends qw/CommonAttributes/;
sub method_controller_one {
my ( $self ) = @_;
warn "method from controller 1";
}
1;
package ControllerTwo;
use Moose;
extends qw/CommonAttributes/;
sub method_controller_two {
my ( $self ) = @_;
warn "method from controller 2";
}
1;
package MyApp;
my $one = ControllerOne->new( name => 'Name: One' );
$one->method_controller_one();
warn $one->name;
$one->jump;
my $two = ControllerTwo->new( name => 'Name Two:' );
warn $two->name;
$two->method_controller_two();
$one->jump;
On 7/21/13, Robert Rothenberg <robrwo at gmail.com> wrote:
> I prefer to put as much code as I can (especially "business logic" code)
> into Moose role methods. This makes it easier to share code among multiple
> controller methods, and it makes the code a little easier to read as well
> as test (since the role methods don't require the Catalyst server to be
> running per se: the context can be simulated using
> CatalystX::Test::MockContext).
>
> If the code really does require a controller, I create a base controller
> class that uses configuration parameters from $self->{config}, and then
> have the actual controllers use something like
>
> __PACKAGE__->config(
> table => 'foo',
> ..
> );
>
>
>
>
>
>
> On Wed, Jul 17, 2013 at 3:05 AM, cc loo <mobile.ccloo at gmail.com> wrote:
>
>> Hi all, i'm a network engineer by trade and is picking up perl/catalyst
>> to
>> upgrade my skills :)
>>
>> I have a couple of controllers each having same methods, chaining off
>> their respective 'base' methods.
>>
>> I build my controllers off this guide here:
>> http://search.cpan.org/~ether/Catalyst-Manual-5.9007/lib/Catalyst/Manual/Tutorial/04_BasicCRUD.pod#Refactor_to_Use_a_'base'_Method_to_Start_the_Chains
>>
>>
>> So, i have
>>
>> controller_a with a method 'list' , chaining off 'base'
>> controller_b with a method 'list', chaining off' 'base'
>>
>> Is there a more graceful manner of inheriting this method instead of
>> copy/paste on every controller i have ?
>>
>>
>> _______________________________________________
>> List: Catalyst at lists.scsys.co.uk
>> Listinfo: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
>> Searchable archive:
>> http://www.mail-archive.com/catalyst@lists.scsys.co.uk/
>> Dev site: http://dev.catalyst.perl.org/
>>
>>
>
More information about the Catalyst
mailing list