3 ms·
Maybe it's just me, but I've never seen a use for traits. Any time I need to reuse logic across classes, I'll make it a proper class and compose it in as a memb
by Joeri 12y ago
Maybe it's just me, but I've never seen a use for traits. Any time I need to reuse logic across classes, I'll make it a proper class and compose it in as a member.
What sort of functionality do you use traits for?
- gamache 12y ago> I'll make it a proper class and compose it in as a member. You've just implemented traits.
- Joeri 12y agoIn PHP traits override methods which is something other than being a member object (though you can use traits to do that as well). http://php.net/manual/en/language.oop5.traits.php http://php.net/manual/en/language.oop5.traits.php
- zsoltgyongyosi 12y agoI used traits to extract common functionality from POPOs.
- wschroed 12y agoThat's a delegation strategy, which is a very limited form of composition. A class with a trait/role can be queried for that interface: smile() if $my_object->does('SomeTrait'); Methods provided by a trait/role have direct access to $self. Also, Moose gives you the ability to apply traits to classes that are not predefined with those traits: use Moose::Util; my $instance = Moose::Util::with_traits('MooseClass', 'MyTrait')->new(%params); You can parameterize roles (as in, pass parameters that affect what the role provides). If you put some method modifiers into your roles, you can enhance existing functionality; for example, you can add logging, memoization, and persistence, all without the class having those features beforehand. In other words, roles/traits make your OOP functionality much more composable.