<?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>Mon, 06 Feb 2012 20:47:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<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>
		<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>
		<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-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

