Rechercher une page de manuel
MooseX::Traits.3pm
Langue: en
Version: 2009-05-28 (debian - 07/07/09)
Section: 3 (Bibliothèques de fonctions)
Sommaire
NAME
MooseX::Traits - automatically apply roles at object creation timeSYNOPSIS
Given some roles:package Role; use Moose::Role; has foo => ( is => 'ro', isa => 'Int' required => 1 );
And a class:
package Class; use Moose; with 'MooseX::Traits';
Apply the roles to the class at "new" time:
my $class = Class->new_with_traits( traits => ['Role'], foo => 42 );
Then use your customized class:
$class->isa('Class'); # true $class->does('Role'); # true $class->foo; # 42
To apply traits to an existing instance:
$self->apply_traits([qw/Role1 Role2/], { rebless_params => 'go here' });
DESCRIPTION
Often you want to create components that can be added to a class arbitrarily. This module makes it easy for the end user to use these components. Instead of requiring the user to create a named class with the desired roles applied, or applying roles to the instance one-by-one, he can just pass a "traits" parameter to the class's "new_with_traits" constructor. This role will then apply the roles in one go, cache the resulting class (for efficiency), and return a new instance. Arguments meant to initialize the applied roles' attributes can also be passed to the constructor.Alternatively, traits can be applied to an instance with "apply_traits", arguments for initializing attributes in consumed roles can be in %$self (useful for e.g. Catalyst components.)
METHODS
- $class->new_with_traits(%args, traits => \@traits)
- $instance->apply_traits($trait => \%args)
- $instance->apply_traits(\@traits => \%args)
ATTRIBUTES YOUR CLASS GETS
This role will add the following attributes to the consuming class._trait_namespace
You can override the value of this attribute with "default" to automatically prepend a namespace to the supplied traits. (This can be overridden by prefixing the trait name with "+".)Example:
package Another::Trait; use Moose::Role; has 'bar' => ( is => 'ro', isa => 'Str', required => 1, ); package Another::Class; use Moose; with 'MooseX::Traits'; has '+_trait_namespace' => ( default => 'Another' ); my $instance = Another::Class->new_with_traits( traits => ['Trait'], # "Another::Trait", not "Trait" bar => 'bar', ); $instance->does('Trait') # false $instance->does('Another::Trait') # true my $instance2 = Another::Class->new_with_traits( traits => ['+Trait'], # "Trait", not "Another::Trait" ); $instance2->does('Trait') # true $instance2->does('Another::Trait') # false
AUTHOR
Jonathan Rockway "<jrockway@cpan.org>"Stevan Little "<stevan.little@iinteractive.com>"
Rafael Kitover "<rkitover@cpan.org>"
COPYRIGHT AND LICENSE
Copyright 2008 Infinity Interactive, Inc.<http://www.iinteractive.com>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Contenus ©2006-2024 Benjamin Poulain
Design ©2006-2024 Maxime Vantorre