<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Perlblogs &#187; moose</title>
	<atom:link href="http://perlblogs.com/category/moose/feed/" rel="self" type="application/rss+xml" />
	<link>http://perlblogs.com</link>
	<description>Posts from selected Perl bloggers</description>
	<lastBuildDate>Fri, 18 May 2012 19:03:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>Loaded for Werewolf</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/loaded-for-werewolf.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/loaded-for-werewolf.html#comments</comments>
		<pubDate>Thu, 08 Mar 2012 23:47:39 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[legends]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=6df64b711c252320a8903d22788346a6</guid>
		<description><![CDATA[Legend has it that Jean Chastel fired two shots and killed the beast of G&#38;eacute;vaudan. The beast attacked livestock and people in south-central France in the middle of the 18th century. Some say the beast killed over a hundred people....]]></description>
			<content:encoded><![CDATA[
        <p>Legend has it that <a
href="http://betedugevaudan.com/en/jean_chastel_en.html">Jean Chastel</a> fired
two shots and killed the <a href="http://betedugevaudan.com/en/">beast of
G&eacute;vaudan</a>.</p>

<p>The beast attacked livestock and people in south-central France in the
middle of the 18th century. Some say the beast killed over a hundred people.
The attacks ended after the deaths of two large wolves&mdash;one in 1765 and
the other by Chastel in 1767.</p>

<p>By the 20th century the legend had grown to include the story that Chastel
had melted down a medallion of the Virgin Mary to make two bullets of
silver.</p>

<p>In 1986, Fred Brooks used this metaphor to propose that no single technology
nor management technique could produce an order of magnitude improvement in
productivity, reliability, or simplicity within the decade. (Most people get
this quote very wrong. Most people haven't read the paper in detail or at
all.)</p>

<p>Perl 1 entered the public world in 1987.</p>

<p>Today (while solving hard problems), I realized that <a
href="http://moose.perl.org/">Moose</a> and its ecosystem&mdash;including
projects it's inspired, such as other declarative mechanisms for describing
classes and objects&mdash;may just represent an order of magnitude improvement
in productivity, reliability, and simplicity.</p>

<p>I write a lot less code. I write less repetitive code. My code is easier to
read and to maintain. My code is much more correct. My code is much more
flexible and easier to test. (Compilation error messages are much worse. That
doesn't bother me terribly, but keep it in mind.)</p>

<p>Keep your blessed hash references all you want and lament that kids these
days don't have to walk uphill in the snow both ways to stuff things in package
global variables like <code>@INC</code> and that we're lazy, fat slobs for
using CPAN modules for what you have done by hand since 1994, just as Moses did
and King James always intended...</p>

<p>... but I'm loaded for werewolf.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/09/loaded-for-werewolf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Memoization of Lazy Attributes</title>
		<link>http://www.modernperlbooks.com/mt/2012/02/the-memoization-of-lazy-attributes.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/02/the-memoization-of-lazy-attributes.html#comments</comments>
		<pubDate>Mon, 27 Feb 2012 18:45:41 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=86f465784ea4372fc5c44358736330ad</guid>
		<description><![CDATA[Great software changes the way you use computers. Great languages, libraries, and tools change the way you code. Moose qualifies as great. Moose includes a feature known as attribute builders. When you declare the attributes of an object, you can...]]></description>
			<content:encoded><![CDATA[
        <p>Great software changes the way you use computers. Great languages, libraries,
and tools change the way you code. <a href="http://moose.perl.org/">Moose</a>
qualifies as great.</p>

<p>Moose includes a feature known as attribute builders. When you declare the
attributes of an object, you can specify default values:</p>

<pre><code>use Moose;

has 'name', is =&gt; 'ro', default =&gt; 'Binky';</code></pre>

<p>When someone builds a new object of this type, they can provide a name for
the object, or get a default name of <code>Binky</code>.</p>

<p>For more dynamic behavior, provide a function reference as the default. For
example, if an object needs to know its creation time (and not the time the
system started):</p>

<pre><code>use Moose;
use DateTime;

has 'birthtime', is =&gt; 'ro', default =&gt; sub { DateTime-&gt;now };</code></pre>

<p>For even more flexibility, you can use the <em>name</em> of a method as the
builder. This allows you to customize the behavior further with a subclass,
role, or other mechanism:</p>

<pre><code>use Moose;
use DateTime;

has 'birthtime', is =&gt; 'ro', builder =&gt; '_build_birthtime';

sub _build_birthtime { DateTime-&gt;now };</code></pre>

<p>Overriding this builder is easy (far easier than intercepting all calls to
the object's constructor.) As another benefit, you know that because Moose
calls this builder during object construction, your object always gets
constructed in a consistent, known-good state. You can rely on it being
<em>correct</em> throughout the rest of its lifespan. (Obviously you have to
avoid poking into it to do the wrong things, but that's up to you.)</p>

<p>This feature in and of itself would be good, but Moose went further to make
it great. If you specify the attribute builder as <em>lazy</em>, Moose will
only call the builder when someone uses the attribute's accessor:</p>

<pre><code>use Moose;
use DateTime;

has 'first_access_time', is   =&gt; 'ro', builder =&gt; '_build_firstaccesstime',
                         lazy =&gt; 1;

sub _build_firstaccesstime { DateTime-&gt;now };</code></pre>

<p>This makes the most sense when calculating an attribute is somehow expensive
or the use of an attribute is rare. For example, I have an object which
represents the calculation and projection of ten year free cash flow growth of
a stock (like earnings, but measures liquid assets and less prone to
manipulation via accrual accounting methods). This object is responsible for
calculating the projected ten year average growth rate in free cash flow and
produces a graph of ten year trailing free cash flow, the trendline for those
ten years and ten years in the future, and projected growth curve ten years in
the future.</p>

<p>That requires some math.</p>

<p>That math has a lot of interdependencies. Finding a good trendline for
earnings which fluctuate means statistical analysis, such as with <a
href="http://search.cpan.org/perldoc?Statistics::Basic::LeastSquareFit">Statistics::Basic::LeastSquareFit</a>.
As it happens, the lazy <code>lsf</code> attribute nicely encapsulates that
statistics object. Further, the growth rate is another lazy attribute, as are
the sets of points of the trendline and the trend curve.</p>

<p>While the original proof of concept of this code performed all of the
calculations in one large function of a couple of hundred lines, the current
code is several methods of 10 - 50 lines apiece, with much better calculation
accuracy, and better factoring. This is all thanks to Moose's lazy
attributes.</p>

<p>The monolithic code was monolithic because I wanted to calculate everything
once and only once: growth rate, number of points on the lines and curves,
everything. Variables would stay in scope over tens and hundreds of lines
because I'd need to use them later.</p>

<p>By factoring individual calculations into their own lazy builders, I can
call the accessors when I need attribute data and everything snaps into place
behind the scenes thanks to Moose. Oh, and if I've already calculated the data
for the object, <em>it's already there</em>, and I don't have to recalculate
it.</p>

<p>Lazy attributes give me <a
href="http://search.cpan.org/perldoc?Memoize">memoization</a> for free, and I
don't even have to think about the data dependency graph of my calculations.
It's an emergent property of the source code. That's one more step in
expressing what I want to happen and not how to make it happen. Thanks,
Moose!</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/02/27/the-memoization-of-lazy-attributes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>You&#8217;re Already Using Dependency Injection</title>
		<link>http://www.modernperlbooks.com/mt/2011/08/youre-already-using-dependency-injection.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/08/youre-already-using-dependency-injection.html#comments</comments>
		<pubDate>Thu, 11 Aug 2011 17:07:18 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[dependencyinjection]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[talks]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=76534268443023b7f1213deb26f63c8d</guid>
		<description><![CDATA[Ben Hengst gave a talk at Portland Perl Mongers last night about dependency injection and inversion of control in Perl. He said something completely true. &#34;You've probably already done this, even though you didn't know it was called this.&#34; At...]]></description>
			<content:encoded><![CDATA[
        <p><a href="http://notbenh.info/">Ben Hengst</a> gave a talk at <a
href="http://pdx.pm.org/">Portland Perl Mongers</a> last night about dependency
injection and inversion of control in Perl. He said something completely true.
"You've probably already done this, even though you didn't know it was called
this."</p>

<p>At its core, dependency injection is a formalization of the design principle "Don't hard-code your dependencies." Consider the code:</p>

<pre><code>sub fetch
{
    my ($self, $uri) = @_;
    my $ua           = LWP::UserAgent-&gt;new;
    my $resp         = $ua-&gt;get( $uri );

    ...
}</code></pre>

<p>That's not <em>bad</em> code by any means, but it's a little too specific
and a little less generic due to the presence of the literal string
<code>LWP::UserAgent</code>. That might be fine for your application, but that
hard-coding introduces a coupling that can work against other uses of this
code. Imagine testing this code, for example. While you <em>could</em> use <a
href="http://search.cpan.org/perldoc?Test::MockObject">Test::MockObject</a> to
intercept calls to <code>LWP::UserAgent</code>'s constructor, that approach
manipulates Perl symbol tables to work around a hard coded dependency.</p>

<p>An alternate approach uses a touch of indirection to allow for greater
genericity:</p>

<pre><code>use Moose;
<strong>has 'ua', is =&gt; 'ro', default =&gt; sub { LWP::UserAgent-&gt;new };</strong>

sub fetch
{
    my ($self, $uri) = @_;
    <strong>my $ua           = $self-&gt;ua;</strong>
    my $resp         = $ua-&gt;get( $uri );

    ...
}</code></pre>

<p>Now the choice of user agent is up to the code which constructs this object.
If it provides a <code>ua</code> to the constructor, <code>fetch()</code> will
use that. Otherwise, the default behavior is to use <code>LWP::UserAgent</code>
as before.</p>

<p>Adding one line of code and changing one line of code has provided much more flexibility.</p>

<p>An alternate approach is to allow setting <code>ua</code> through an
accessor instead of a constructor, but as far as I can tell the only reason to
do this is if you're stuck in <a href="http://www.bartleby.com/42/638.html">The
Land of the Java Bean Eaters</a>.</p>

<p>While the existing literature on inversion of control and dependency
injection tends to throw around big words which have the effect of obfuscating
rather than enlightening, the basic concepts is simple. You've probably already
done it. Now you know what it's called and why it's useful, and probably also
can find ways to use it where it helps.</p>

<p><em>(See also: how you select a DBD with <a href="http://search.cpan.org/perldoc?DBI">DBI</a>.)</em></p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/08/11/youre-already-using-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Catalyst Session Flash Methody</title>
		<link>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html#comments</comments>
		<pubDate>Thu, 09 Jun 2011 22:08:32 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/06/making-catalyst-session-flash-methody.html</guid>
		<description><![CDATA[I have a handful of modest Catalyst applications and will undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much is that it's reasonably easy to solve a problem experienced in multiple places, extract that...]]></description>
			<content:encoded><![CDATA[
        <p>I have a handful of modest <a
href="http://catalystframework.org/">Catalyst</a> applications and will
undoubtedly have more. One of the reasons I enjoy working with Perl 5 so much
is that it's reasonably easy to solve a problem experienced in multiple places,
extract that solution, and generalize and publish it for other people. The
modern Perl world only makes that easier with Moose, CPAN, and even Github.</p>

<p>Sometimes that ease moves the problem around, which reinforces the notion
that the only two hard problems in computer science are naming and caching. To
abuse that truism, once I've found a workable solution, the hard part is
figuring out what to call it and how to make it available to other people.</p>

<p>Take the <em>flash</em> feature of Catalyst's <a
href="http://search.cpan.org/perldoc?Catalyst::Plugin::Session">Catalyst::Plugin::Session</a>.
It resembles the stash, in that you can store and retrieve information in and
from the flash, but that data is only available until the first request which
uses it. This is incredibly handy for user notifications, such as "You missed a
required entry field!" or "Your interaction succeeded!", especially when
combined with the <a href="http://wavded.github.com/humane-js/">Humane JS
library</a>.</p>

<p>My controller actions have a pattern:</p>

<pre><code>sub edit :Chained( 'get_widget' ) :PathPart('edit') :Args(0)
{
    my ($self, $c) = @_;

    return unless lc $c-&gt;req-&gt;method eq 'post';

    my $params = $c-&gt;req-&gt;params;
    my $widget   = $c-&gt;stash-&gt;{widget};

    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        push @{ $c->flash->{messages} }, 'Updated widget!';
    }
    catch { push @{ $c->flash->{errors} }, $_ };

    return $c-&gt;res-&gt;redirect(
        $c-&gt;uri_for( $c-&gt;controller( 'Widgets' )
          -&gt;action_for( 'index' ) )
    );
}</code></pre>

<p>Yet every time I write that code, it feels slightly wrong, as if I'm
violating encapsulation by updating the variable <em>behind</em> the flash
directly. It's also prone to typos and has the whiff of violating the <a href="http://c2.com/cgi/wiki?LawOfDemeter">Law of Demeter</a>.</p>

<p>I prefer instead to write:</p>

<pre><code>    try
    {
        $widget-&gt;$_( $params-&gt;{$_} ) for $widget-&gt;editable_fields;
        $widget-&gt;update;
        <strong>$c-&gt;add_message( 'Updated widget!' );</strong>
    }
    catch { <strong>$c-&gt;add_error( $_ )</strong> };</code></pre>

<p>... where my actions don't have to know about the internals of <em>how</em>
the flash stores its data, where I don't have the possibility of stomping all
over the array references accidentally, and where I can replace syntax (the
grotty Perl 5 reference syntax!) with a method which describes my intent.</p>

<p>The simplest way to make this work is:</p>

<pre><code>package Catalyst::Plugin::Session::FlashMethods;
# ABSTRACT: add flash-manipulation methods to Catalyst::Plugin::Session

use parent 'Catalyst::Plugin::Session';

use Modern::Perl;

sub add_message
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{messages} }, @_;
}

sub add_error
{
    my $self = shift;
    push @{ $self-&gt;flash-&gt;{errors} }, @_;
}

1;</code></pre>

<p>... and load it in my applications with:</p>

<pre><code>use Catalyst::Plugin::ConfigLoader;
use Catalyst::Plugin::Static::Simple;
<strong>use Catalyst::Plugin::Session::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    ConfigLoader
    Static::Simple
    <strong>Session::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>This approach has (at least) two problems. First, while I'm happy to make
this code available to other developers, I don't want to add any difficulties
to use other plugins which may themselves extend or modify
<code>Catalyst::Plugin::Session</code>.</p>

<p>Second, this code is awfully specific to my own uses. I believe those uses
could help other people, but why solve a problem so specific when genericity
and wider applicability are possible?</p>

<p>Rephrasing the problem might help.</p>

<p>I have a hash. I want named methods to store application-specific data in
that hash. I would like the ability to customize that set of methods methods
without hard-coding them, so as to produce a component that multiple people can
reuse in multiple applications.</p>

<p>You can see why a big bag of untyped stuff (a hash) is useful.</p>

<p>What I really need is a way to say "My application will use these and only
these specific elements of the flash, so please produce methods for them."
Fortunately, I have one in <a
href="http://search.cpan.org/perldoc?MooseX::Role::Parameterized">MooseX::Role::Parameterized</a>.
The consumer of this code looks like:</p>

<pre><code>package MyApp::Catalyst::Plugin::FlashMethods;
# ABSTRACT: role to add flash-manipulation methods to Catalyst app

use Moose;

extends 'Catalyst::Plugin::Session';
with 'Catalyst::Plugin::Role::FlashMethods'
    =&gt; { flash_elements =&gt; [qw( message error )] };

1;</code></pre>

<p>... and it gets enabled in my Catalyst application with:</p>

<pre><code><strong>use MyApp::Catalyst::Plugin::FlashMethods;</strong>
use Catalyst::Plugin::Session::State::Cookie;
use Catalyst::Plugin::Session::Store::FastMmap;

use Catalyst qw/
    -Debug
    ConfigLoader
    Static::Simple
    <strong>+MyApp::Catalyst::Plugin::FlashMethods</strong>
    Session::State::Cookie
    Session::Store::FastMmap
/;</code></pre>

<p>... which consumes the parametric role:</p>

<pre><code>package Catalyst::Plugin::Role::FlashMethods;

use MooseX::Role::Parameterized;

parameter 'flash_elements', isa =&gt; 'ArrayRef[Str]', required =&gt; 1;

role
{
    my $p = shift;

    for my $element (@{ $p-&gt;flash_elements })
    {
        method "add_${element}" =&gt; sub
        {
            my $self = shift;
            push @{ $self-&gt;flash-&gt;{ $element . 's' } }, @_;
        };
    }
};

1;</code></pre>

<p>This code does have some na&iuml;ve in it. In particular, it ought to use a
smarter pluralization scheme. As well, the interface bothers me in two places.
I'm not sure that the module's name is correct. I also don't particularly like
that using this role means creating a new class of ~10 lines to make the code
available as a Catalyst plugin (though how one might expand Catalyst's
<code>import()</code> to understand how to reify a parametric role given the
appropriate parameters is beyond my language design skills today).</p>

<p>Then again, my ~10 line plugin which consumes this role <em>does</em> work
across my multiple Catalyst applications, at the cost of one more file and nine
more lines of code altogether. The ratio of code per method decreases
substantially with each new method I add, though.</p>

<p>I had originally intended to improve stash handling in this fashion, but but
that's much more work. Neither Catalyst's core nor any other plugin I currently
use rely on the presence of flash, so the scope of this work was much smaller.
Even if they did, this approach does not prevent anything else from poking into
the flash for good or ill.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/06/10/making-catalyst-session-flash-methody-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

