Perl Dancer + mysql + memcached
Most of the people writing Perl have heard about the Perl Dancer micro-framework. But did they use it for anything beyond generating a project, writing a ‘Hello world’ route and starting it?
Meanwhile this web framework is quite functional and fast. Sessions, database, caching, sending mail, routes, layout and templates - what else do you need to get a small project running quickly?
Creating a new, almost empty project is simple:
dancer -a AppName
You get the ./AppName directory with the application in it. Start it like this:
cd AppName
bin/app.pl
The application is now available at http://0.0.0.0:3000
I put not only Dancer itself into the title, but MySQL and Memcached as well. So let’s make them work together.
The database connection goes into the ./config.yml config file, in the Plugins - Database section:
plugins:
Database:
driver: 'mysql'
database: 'basename'
host: 'localhost'
port: 3306
username: 'user'
password: 'userPassword'
The memcached connection is configured in the same place:
Memcached:
servers:
- "127.0.0.1:11211"
default_timeout: 10
Where the cookies are stored is also defined here:
session: "cookie"
session_cookie_key: "m5M7gM3rH4BFOd782fPo3iiom33W77P5ytE1zHqJijG3GqxL"
Now we can use all of this in the application:
package App;
use Dancer ':syntax';
use Dancer::Plugin::Database;
use Dancer::Plugin::Memcached;
get '/' => sub {
my $m_root = memcached_get('page-root');
unless ($m_root) {
my $data;
my $m_data = memcached_get('root-page-select');
unless ($m_data) {
$data = database->quick_select('table', { col => 'variable' }, { limit => 20 });
} else {
$data = $m_data;
}
# code
memcached_store 'root-page', \@rootPage;
} else {
@rootPage = @{$m_root};
}
template 'templateName', { var => \@rootPage };
};
Something like that. In this piece of code I showed two cases of caching - caching all the variables that go to the template engine, and caching only the query. Pick the one you need in your particular situation.
By the way, with Dancer I use the TemplateToolkit template engine, but after I tried Sinatra/Haml I started to look at it completely differently.