NAME
Sub::Mage::Spellbook - Recipes for Sub::Mage
IMPORTS
We'll start with import attributes seems that they are created at the beginning when we use Sub::Mage
. Generally they will be in the form of an array, as such:
use Sub::Mage qw/:5.010 :Debug :Moose/;
The first option :5.010
imports the 5.010 feature (so you can use "say" and "given"), the second :Debug
turns on debugging, and the last one we used :Moose
lets Sub::Mage know that you're using Moose, so don't import overide
, after
and before
as Moose already has these features. And Moose is great. Another handy import attribute is :Class
. Please read below about Controlling a Class remotely to see how it works.
Controlling a Class remotel
Sub::Mage makes this easy with its array of methods.
First, let's create a blank package and turn it into our class. When using :Class
it removes the need to add sub new { ... }
and also imports some other handy methods, like augment
and accessor
.
package Spells;
use Sub::Mage qw/:Class/;
1;
That's our whole class.. now, let's control it from merlin.pl
use Spells;
my $spells = Spells->new;
# create a method called 'fireball' in Spells
Spells->conjur( fireball => sub {
my $self = shift;
$self->{damage} = 5;
});
# create an accessor method called 'damage_of_fireball'
Spells->conjur( damage_of_fireball => sub {
return shift->{damage};
});
$spells->fireball;
print $spells->damage_of_fireball; # returns 5
Notice how we didn't even need to load Sub::Mage
in merlin.pl
? This is because we used everything from the Spells
class. We've created the subroutine fireball
but we want to let people create their own damage modifier and make it verbose..
Spells->override( fireball => sub {
my ($self, $val) = @_;
$self->{damage} = $val;
});
Oh, we forgot to make it verbose. Let's just tag it on the end...
Spells->after( fireball => sub {
my ($self, $val) = @_;
print "Damage set to $val\n";
});
So now we call..
$spells->fireball(10);
And see Damage set to 10
. And that's how you can control a blank class remotely. Useless, but interesting.