Download presentation
Presentation is loading. Please wait.
Published byPhillip Griffin Modified over 8 years ago
1
Introducing Modern Perl Dave Cross Magnum Solutions Ltd dave@mag-sol.com
2
YAPC::Europe 2nd August 2010 2 Modern Perl Perl has been around for a long time Achieved great popularity in the 1990s “The duct tape of the internet” Perl has moved on a lot since then Many people's perceptions of Perl haven't
3
YAPC::Europe 2nd August 2010 3 Modern Perl Keeping up to date with Perl Surveying modern modules and techniques A lot to cover Only an overview Plenty of pointers to more information
4
YAPC::Europe 2nd August 2010 4 What We Will Cover Template Toolkit DateTime DBIx::Class TryCatch
5
YAPC::Europe 2nd August 2010 5 What We Will Cover Moose autodie Catalyst PSGI/Plack
6
YAPC::Europe 2nd August 2010 6 Schedule 09:00 – Begin 11:00 – Coffee break 13:00 – Lunch 14:00 – Begin 16:00 – Coffee break 17:00 – End
7
YAPC::Europe 2nd August 2010 7 Resources Slides available on-line – http://mag-sol.com/train/yapc/2010 Also see Slideshare – http://www.slideshare.net/davorg/slideshows Get Satisfaction – http://getsatisfaction.com/magnum
8
Template Toolkit
9
YAPC::Europe 2nd August 2010 9 Templates Many people use templates to produce web pages Advantages are well known Standard look and feel (static/dynamic) Reusable components Separation of code logic from display logic Different skill-sets (HTML vs Perl)
10
YAPC::Europe 2nd August 2010 10 DIY Templating Must be easy - so many people do it See perlfaq4 “How can I expand variables in text strings?”
11
YAPC::Europe 2nd August 2010 11 DIY Templating $text = 'this has a $foo in it and a $bar'; %user_defs = ( foo => 23, bar => 19, ); $text =~ s/\$(\w+)/$user_defs{$1}/g; Don't do that
12
YAPC::Europe 2nd August 2010 12 Templating Options Dozens of template modules on CPAN Text::Template, HTML::Template, Mason, Template Toolkit Many, many more Questions to consider – HTML only? – Template language
13
YAPC::Europe 2nd August 2010 13 Template Toolkit http://tt2.org/ Very powerful Both web and non-web Simple template language Plugins give access to much of CPAN Can use Perl code if you want – But don't do that
14
YAPC::Europe 2nd August 2010 14 Good Book Too!
15
YAPC::Europe 2nd August 2010 15 The Template Equation Data + Template = Output Data + Alternative Template = Alternative Output Different views of the same data Only the template changes
16
YAPC::Europe 2nd August 2010 16 Simple TT Example use Template; use My::Object; my ($id, $format) = @ARGV; $format ||= 'html'; my $obj = My::Object->new($id) or die; my $tt = Template->new; $tt->process("$format.tt", { obj => $obj }, "$id.$format") or die $tt->error;
17
YAPC::Europe 2nd August 2010 17 html.tt [% obj.name %] [% obj.name %] [% obj.desc %] [% FOREACH child IN obj.children -%] [% child.name %] [% END %]
18
YAPC::Europe 2nd August 2010 18 text.tt [% obj.name | upper %] Image: [% obj.img %] [% obj.desc %] [% FOREACH child IN obj.children -%] * [% child.name %] [% END %]
19
YAPC::Europe 2nd August 2010 19 Adding New Formats No new code required Just add new output template Perl programmer need not be involved
20
YAPC::Europe 2nd August 2010 20 Equation Revisited Data + Template = Output – Template Toolkit Template + Output = Data – Template::Extract Data + Output = Template – Template::Generate
21
DateTime
22
YAPC::Europe 2nd August 2010 22 Dates & Times Perl has built-in functions to handle dates and times time – seconds since 1st Jan 1970 localtime – convert to human-readable timelocal (in Time::Local) – inverse of localtime strftime (in POSIX) – formatting dates and times
23
YAPC::Europe 2nd August 2010 23 Dates & Times on CPAN Look to CPAN for a better answer Dozens of date/time modules on CPAN Date::Manip is almost never what you want Date::Calc, Date::Parse, Class::Date, Date::Simple, etc Which one do you choose?
24
YAPC::Europe 2nd August 2010 24 Perl DateTime Project http://datetime.perl.org/ "The DateTime family of modules present a unified way to handle dates and times in Perl" "unified" is good Dozens of modules that work together in a consistent fashion
25
YAPC::Europe 2nd August 2010 25 Using DateTime use DateTime; my $dt = DateTime->now; say $dt; # 2010-08-02T10:06:07 say $dt->dmy; # 2010-08-02 say $dt->hms; # 10:06:07
26
YAPC::Europe 2nd August 2010 26 Using DateTime use DateTime; my $dt = DateTime->new(year => 2010, month => 8, day => 2); say $dt->ymd('/'); # 2010/08/02 say $dt->month; # 8 say $dt->month_name; # August
27
YAPC::Europe 2nd August 2010 27 Arithmetic A DateTime object is a point in time For date arithmetic you need a duration Number of years, weeks, days, etc
28
YAPC::Europe 2nd August 2010 28 Arithmetic use DateTime; my $dt = DateTime->new(year => 2010, month => 8, day => 2); my $two_weeks = DateTime::Duration->new(weeks => 2); $dt += $two_weeks; say $dt; # 2010-08-16T00:00:00
29
YAPC::Europe 2nd August 2010 29 Formatting Output use DateTime; my $dt = DateTime->new(year => 2010, month => 4, day => 14); say $dt->strftime('%A, %d %B %Y'); # Wednesday, 14 April 2010 strftime uses UNIX standards Control input format with DateTime::Format::Strptime
30
YAPC::Europe 2nd August 2010 30 Parsing & Formatting Ready made parsers and formatters for popular date and time formats DateTime::Format::HTTP DateTime::Format::MySQL DateTime::Format::Excel DateTime::Format::Baby – the big hand is on...
31
YAPC::Europe 2nd August 2010 31 Alternative Calendars Handling non-standard calendars DateTime::Calendar::Julian DateTime::Calendar::Hebrew DateTime::Calendar::Mayan DateTime::Fiction::JRRTolkien::Shire
32
YAPC::Europe 2nd August 2010 32 Calendar Examples use DateTime::Calendar::Mayan; my $dt = DateTime::Calendar::Mayan->now; say $dt->date; # 12.19.17.9.13 use DateTime::Fiction::JRRTolkien::Shire; my $dt = DateTime::Fiction::JRRTolkien::Shire->now; say $dt->on_date; # Trewsday 14 Afterlithe 7474
33
DBIx::Class
34
YAPC::Europe 2nd August 2010 34 Object Relational Mapping Mapping database relations into objects Tables (relations) map onto classes Rows (tuples) map onto objects Columns (attributes) map onto attributes Don't write SQL
35
YAPC::Europe 2nd August 2010 35 SQL Is Tedious Select the id and name from this table Select all the details of this row Select something about related tables Update this row with these values Insert a new record with these values Delete this record
36
YAPC::Europe 2nd August 2010 36 Replacing SQL Instead of SELECT * FROM my_table WHERE my_id = 10 and then dealing with the prepare/execute/fetch code
37
YAPC::Europe 2nd August 2010 37 Replacing SQL We can write use My::Object; # warning! not a real orm my $obj = My::Object->retrieve(10) Or something similar
38
YAPC::Europe 2nd August 2010 38 Writing An ORM Layer Not actually that hard to do yourself Each class needs an associated table Each class needs a list of columns Create simple SQL for basic CRUD operations Don't do that
39
YAPC::Europe 2nd August 2010 39 Perl ORM Options Plenty of choices on CPAN Class::DBI Rose::DB::Object ORLite DBIx::Class – The current favourite Fey::ORM
40
YAPC::Europe 2nd August 2010 40 DBIx::Class Standing on the shoulders of giants Learning from problems in Class::DBI More flexible More powerful
41
YAPC::Europe 2nd August 2010 41 DBIx::Class Example Modeling a CD collection Three tables artist (artistid, name) cd (cdid, artist, title) track (trackid, cd, title)
42
YAPC::Europe 2nd August 2010 42 Main Schema Define main schema class Music/DB.pm package Music::DB; use base qw/DBIx::Class::Schema/; __PACKAGE__->load_classes(); 1;
43
YAPC::Europe 2nd August 2010 43 Object Classes - Artist Music/DB/Artist.pm package Music::DB::Artist; use base qw/DBIx::Class/; __PACKAGE__->load_components(qw/Core/); __PACKAGE__->table('artist'); __PACKAGE__->add_columns(qw/ artistid name /); __PACKAGE__->set_primary_key('artistid'); __PACKAGE__->has_many(cds => 'Music::DB::Cd'); 1;
44
YAPC::Europe 2nd August 2010 44 Object Classes- CD Music/DB/CD.pm package Music::DB::CD; use base qw/DBIx::Class/; __PACKAGE__->load_components(qw/Core/); __PACKAGE__->table('cd'); __PACKAGE__->add_columns(qw/ cdid artist title year /); __PACKAGE__->set_primary_key('cdid'); __PACKAGE__->belongs_to( artist => 'Music::DB:Artist'); 1;
45
YAPC::Europe 2nd August 2010 45 Inserting Artists my $schema = Music::DB->connect($dbi_str); my @artists = ('Florence + The Machine', 'Belle and Sebastian'); my $art_rs = $schema->resultset('Artist'); foreach (@artists) { $art_rs->create({ name => $_ }); }
46
YAPC::Europe 2nd August 2010 46 Inserting CDs Hash of Artists and CDs my %cds = ( 'Lungs' => 'Florence + The Machine', 'The Boy With The Arab Strap' => 'Belle and Sebastian', 'Dear Catastrophe Waitress' => 'Belle and Sebastian', );
47
YAPC::Europe 2nd August 2010 47 Inserting CDs Find each artist and insert CD foreach (keys $cds) { my ($artist) = $art_rs->search( { name => $cds{$_} } ); $artist->add_to_cds({ title => $_, }); }
48
YAPC::Europe 2nd August 2010 48 Retrieving Data Get CDs by artist my $name = 'Belle and Sebastian'; my ($artist) = $art_rs->search({ name => $name, }); foreach ($artist->cds) { say $_->title; }
49
YAPC::Europe 2nd August 2010 49 Searching for Data Search conditions can be more complex Alternatives $rs->search({year => 2006}, {year => 2007}); Like – $rs->search({name => { 'like', 'Dav%' }});
50
YAPC::Europe 2nd August 2010 50 Searching for Data Combinations $rs->search({forename => { 'like', 'Dav%' }, surname => 'Cross' });
51
YAPC::Europe 2nd August 2010 51 Don't Repeat Yourself There's a problem with this approach Information is repeated Columns and relationships defined in the database schema Columns and relationships defined in class definitions
52
YAPC::Europe 2nd August 2010 52 Repeated Information CREATE TABLE artist ( artistid INTEGER PRIMARY KEY, name TEXT NOT NULL );
53
YAPC::Europe 2nd August 2010 53 Repeated Information package Music::DB::Artist; use base qw/DBIx::Class/; __PACKAGE__->load_components(qw/Core/); __PACKAGE__->table('artist'); __PACKAGE__->add_columns(qw/ artistid name /); __PACKAGE__->set_primary_key('artistid'); __PACKAGE__->has_many(cds => 'Music::DB::Cd'); 1;
54
YAPC::Europe 2nd August 2010 54 Database Metadata Some people don't put enough metadata in their databases Just tables and columns No relationships. No constraints You may as well make each column VARCHAR(255)
55
YAPC::Europe 2nd August 2010 55 Database Metadata Describe your data in your database It's what your database is for It's what your database does best
56
YAPC::Europe 2nd August 2010 56 No Metadata (Excuse 1) "This is the only application that will ever access this database" Nonsense All data will be shared eventually People will update your database using other applications Can you guarantee that someone won't use mysql to update your database?
57
YAPC::Europe 2nd August 2010 57 No Metadata (Excuse 2) "Database doesn't support those features" Nonsense MySQL 3.x is not a database – It's a set of data files with a vaguely SQL-like query syntax MySQL 4.x is a lot better MySQL 5.x is most of the way there Don't be constrained by using inferior tools
58
YAPC::Europe 2nd August 2010 58 DBIC::Schema::Loader Creates classes by querying your database metadata No more repeated data We are now DRY Schema definitions in one place But... Performance problems
59
YAPC::Europe 2nd August 2010 59 Performance Problems You don't really want to generate all your class definitions each time your program is run Need to generate the classes in advance dump_to_dir method Regenerate classes each time schema changes
60
YAPC::Europe 2nd August 2010 60 Alternative Approach Need one canonical definition of the data tables Doesn't need to be SQL DDL Could be Perl code Generate DDL from DBIx::Class definitions – Harder approach – Might need to generate ALTER TABLE
61
YAPC::Europe 2nd August 2010 61 Conclusions ORM is a bridge between relational objects and program objects Avoid writing SQL in common cases DBIx::Class is the currently fashionable module Caveat: ORM may be overkill for simple programs
62
YAPC::Europe 2nd August 2010 62 More Information Manual pages (on CPAN) DBIx::Class DBIx::Class::Manual::* DBIx::Class::Schema::Loader Mailing list (Google for it)
63
TryCatch
64
YAPC::Europe 2nd August 2010 64 Error Handling How do you handle errors in your code? Return error values from subroutines sub get_object { my ($class, $id) = @_; if (my $obj = find_obj_in_db($id)) { return $obj; } else { return; } }
65
YAPC::Europe 2nd August 2010 65 Problems What if someone doesn't check return code? my $obj = MyClass->get_object(100); print $obj->name; # error Caller assumes that $obj is a valid object Bad things follow
66
YAPC::Europe 2nd August 2010 66 Basic Exceptions Throw an exception instead sub get_object { my ($class, $id) = @_; if (my $obj = find_obj_in_db($id)) { return $obj; } else { die “No object found with id: $id”; } } Now caller has to deal with exceptions
67
YAPC::Europe 2nd August 2010 67 Dealing with Exceptions Use eval to catch exceptions my $obj = eval { MyClass->get_object(100) }; if ($@) { # handle exception... } else { print $obj->name; # error }
68
YAPC::Europe 2nd August 2010 68 Exceptions as Objects $@ can be set to an object sub get_object { my ($class, $id) = @_; if (my $obj = find_obj_in_db($id)) { return $obj; } else { die MyException->new( type => 'obj_not_found', id => $id, ); } }
69
YAPC::Europe 2nd August 2010 69 Try Catch TryCatch adds “syntactic sugar” try {... } catch ($e) {... } Looks a lot like many other languages
70
YAPC::Europe 2nd August 2010 70 TryCatch with Scalar try { some_function_that_might_die(); } catch ($e) { if ($e =~ /some error/) { # handle error } else { die $e; } }
71
YAPC::Europe 2nd August 2010 71 TryCatch with Object try { some_function_that_might_die(); } catch ($e) { if ($e->type eq 'file') { # handle error } else { die $e; } }
72
YAPC::Europe 2nd August 2010 72 Better Checks try { some_function_that_might_die(); } catch (My::Error $e) { # handle error }
73
YAPC::Europe 2nd August 2010 73 Even Better Checks try { some_function_that_might_die(); } catch (HTTP::Error $e where { $e->code == 404 }) { # handle 404 error }
74
YAPC::Europe 2nd August 2010 74 Multiple Checks try { some_function_that_might_die(); } catch (HTTP::Error $e where { $e->code == 404 }) { # handle 404 error } catch (HTTP::Error $e where { $e->code == 500 }) { # handle 500 error } catch (HTTP::Error $e) { # handle other HTTP error } catch ($e) { # handle other error }
75
YAPC::Europe 2nd August 2010 75 More Information perldoc TryCatch See also Try::Tiny
76
Moose
77
YAPC::Europe 2nd August 2010 77 Moose A complete modern object system for Perl 5 Based on Perl 6 object model Built on top of Class::MOP – MOP - Meta Object Protocol – Set of abstractions for components of an object system – Classes, Objects, Methods, Attributes An example might help
78
YAPC::Europe 2nd August 2010 78 Moose Example package Point; use Moose; has 'x' => (isa => 'Int', is => 'ro'); has 'y' => (isa => 'Int', is => 'rw'); sub clear { my $self = shift; $self->{x} = 0; $self->y(0); }
79
YAPC::Europe 2nd August 2010 79 Understanding Moose There's a lot going on here use Moose – Loads Moose environment – Makes our class a subclass of Moose::Object – Turns on strict and warnings
80
YAPC::Europe 2nd August 2010 80 Creating Attributes has 'x' => (isa => 'Int', is => 'ro') – Creates an attribute called 'x' – Constrainted to be an integer – Read-only accessor has 'y' => (isa => 'Int', is => 'rw')
81
YAPC::Europe 2nd August 2010 81 Defining Methods sub clear { my $self = shift; $self->{x} = 0; $self->y(0); } Standard method syntax Uses generated method to set y Direct hash access for x
82
YAPC::Europe 2nd August 2010 82 Subclassing package Point3D; use Moose; extends 'Point'; has 'z' => (isa => 'Int'); after 'clear' => sub { my $self = shift; $self->{z} = 0; };
83
YAPC::Europe 2nd August 2010 83 Subclasses extends 'Point' – Similar to use base – Overwrites @ISA instead of appending has 'z' => (isa = 'Int') – Adds new attribute 'z' – No accessor function - private attribute
84
YAPC::Europe 2nd August 2010 84 Extending Methods after 'clear' => sub { my $self = shift; $self->{z} = 0; }; New clear method for subclass Called after method for superclass Cleaner than $self->SUPER::clear()
85
YAPC::Europe 2nd August 2010 85 Creating Objects Moose classes are used just like any other Perl class $point = Point->new(x => 1, y => 2); $p3d = Point3D->new(x => 1, y => 2, z => 3);
86
YAPC::Europe 2nd August 2010 86 More About Attributes Use the has keyword to define your class's attributes has 'first_name' => ( is => 'rw' ); Use is to define rw or ro Omitting is gives an attribute with no accessors
87
YAPC::Europe 2nd August 2010 87 Getting & Setting By default each attribute creates a method of the same name. Used for both getting and setting the attribute $dave->first_name('Dave'); say $dave->first_name;
88
YAPC::Europe 2nd August 2010 88 Change Accessor Name Change accessor names using reader and writer has 'name' => ( is => 'rw', reader => 'get_name', writer => 'set_name', ); See also MooseX::FollowPBP
89
YAPC::Europe 2nd August 2010 89 Required Attributes Moose class attributes are optional Change this with required has 'name' => ( is => 'ro', required => 1, ); Forces constructor to expect a name Although that name could be undef
90
YAPC::Europe 2nd August 2010 90 Attribute Defaults Set a default value for an attribute with default has 'size' => ( is => 'rw', default => 'medium', ); Can use a subroutine reference has 'size' => ( is => 'rw', default => \&rand_size, );
91
YAPC::Europe 2nd August 2010 91 Attribute Properties lazy – Only populate attribute when queried trigger – Subroutine called after the attribute is set isa – Set the type of an attribute Many more
92
YAPC::Europe 2nd August 2010 92 More Moose Many more options Support for concepts like delegation and roles Powerful plugin support – MooseX::* Lots of work going on in this area
93
autodie
94
YAPC::Europe 2nd August 2010 94 More on Exceptions Exceptions force callers to deal with error conditions But you have to explicitly code to throw exceptions open my $fh, '<', 'somefile.txt' or die $!; What if you forget to check the return value?
95
YAPC::Europe 2nd August 2010 95 Not Checking Errors open my $fh, ' ) { # do something useful } If the 'open' fails, you can't read any data You might not even get any warnings
96
YAPC::Europe 2nd August 2010 96 Automatic Exceptions use Fatal qw(open); Comes with Perl since 5.003 Errors in built-in functions become fatal errors This solves our previous problem open my $fh, '<', 'somefile.txt';
97
YAPC::Europe 2nd August 2010 97 However Fatal.pm has its own problems Unintelligent check for success or failure Checks return value for true/false Assumes false is failure Can't be used if function can legitimately return a false value – e.g. fork
98
YAPC::Europe 2nd August 2010 98 Also Nasty error messages $ perl -MFatal=open -E'open my $fh, "notthere"' Can't open(GLOB(0x86357a4), notthere): No such file or directory at (eval 1) line 4 main::__ANON__('GLOB(0x86357a4)', 'notthere') called at -e line 1
99
YAPC::Europe 2nd August 2010 99 Enter autodie autodie is a cleverer Fatal In Perl core since 5.10.1 Fatal needed a list of built-ins autodie assumes all built-ins – use autodie;
100
YAPC::Europe 2nd August 2010 100 Turning autodie on/off Lexically scoped – use autodie; – no autodie; Turn off for specific built-ins – no autodie 'open';
101
YAPC::Europe 2nd August 2010 101 Failing Calls autodie has more intelligence about failing calls Not just a boolean check Understands fork, system, etc
102
YAPC::Europe 2nd August 2010 102 Errors are Objects Errors thrown by autodie are objects Can be inspected for details of the error try { open my $fh, ' args->[-1], "\n"; warn 'File: ', $e->file, "\n"; warn 'Function: ', $e->function, "\n"; warn 'Package: ', $e->package, "\n"; warn 'Caller: ', $e->caller, "\n"; warn 'Line: ', $e->line, "\n"; }
103
YAPC::Europe 2nd August 2010 103 Nicer Errors Too $ perl -Mautodie -E'open my $fh, "not- there"' Can't open($fh, 'not-there'): No such file or directory at -e line 1
104
YAPC::Europe 2nd August 2010 104 More Information perldoc Fatal perldoc autodie autodie - The art of Klingon Programming – http://perltraining.com.au/tips/2008-08-20.html
105
Catalyst
106
YAPC::Europe 2nd August 2010 106 MVC Frameworks MVC frameworks are a popular way to write applications – Particularly web applications
107
YAPC::Europe 2nd August 2010 107 M, V and C Model – Data storage & data access View – Data presentation layer Controller – Business logic to glue it all together
108
YAPC::Europe 2nd August 2010 108 MVC Examples Ruby on Rails Django (Python) Struts (Java) CakePHP Many examples in most languages Perl has many options
109
YAPC::Europe 2nd August 2010 109 MVC in Perl Maypole – The original Perl MVC framework CGI::Application – Simple MVC for CGI programming Jifty – Developed and used by Best Practical Catalyst – Currently the popular choice
110
YAPC::Europe 2nd August 2010 110 Newer MVC in Perl Dancer Squatting Mojolicious
111
YAPC::Europe 2nd August 2010 111 Catalyst MVC framework in Perl Building on other heavily-used tools Model uses DBIx::Class View uses Template Toolkit These are just defaults Can use anything you want
112
YAPC::Europe 2nd August 2010 112 Simple Catalyst App Assume we already have model – CD database from DBIx::Class section Use catalyst.pl to create project $ catalyst.pl CD created "CD" created "CD/script" created "CD/lib" created "CD/root"... many more...
113
YAPC::Europe 2nd August 2010 113 What Just Happened? Catalyst just generated a lot of useful stuff for us Test web servers – Standalone and FastCGI Configuration files Test stubs Helpers for creating models, views and controllers
114
YAPC::Europe 2nd August 2010 114 A Working Application We already have a working application $ CD/script/cd_server.pl... lots of output [info] CD powered by Catalyst 5.7015 You can connect to your server at http://localhost:3000 Of course, it doesn't do much yet
115
YAPC::Europe 2nd August 2010 115 Simple Catalyst App
116
YAPC::Europe 2nd August 2010 116 Next Steps Use various helper programs to create models and views for your application Write controller code to tie it all together Many plugins to handle various parts of the process – Authentication – URL resolution – Session handling – etc...
117
YAPC::Europe 2nd August 2010 117 Create a View $ script/cd_create.pl view Default TT exists "/home/dave/training/cdlib/CD/script/../lib/CD/View " exists "/home/dave/training/cdlib/CD/script/../t" created "/home/dave/training/cdlib/CD/script/../lib/CD/View /Default.pm" created "/home/dave/training/cdlib/CD/script/../t/view_Defa ult.t"
118
YAPC::Europe 2nd August 2010 118 Remove Default Message In lib/CD/Controller/Root.pm sub index :Path :Args(0) { my ( $self, $c ) = @_; # Hello World $c->response_body($c->welcome_message); } Remove response_body line Default behaviour is to render index.tt Need to create that
119
YAPC::Europe 2nd August 2010 119 index.tt root/index.tt CDs [% FOREACH cd IN [ 1.. 10 ] %] CD [% cd %] [% END %]
120
YAPC::Europe 2nd August 2010 120 New Front Page
121
YAPC::Europe 2nd August 2010 121 Adding Data Of course that's hard-coded data Need to add a model class And then more views And some controllers There's a lot to do I recommend working through a tutorial
122
YAPC::Europe 2nd August 2010 122 Easier Catalyst A lot of web applications do similar things Given a database Produce screens to edit the data Surely most of this can be automated It's called Catalyst::Plugin::AutoCRUD (Demo)
123
YAPC::Europe 2nd August 2010 123 Cat::Plugin::AutoCRUD Does a lot of work On the fly For every request No security on table updates So it's not right for every project Very impressive though
124
YAPC::Europe 2nd August 2010 124 Conclusions There's a lot to bear in mind when writing a web app Using the right framework can help Catalyst is the most popular Perl framework As powerful as any other framework – In any language Lots of work still going on Large team, active development
125
YAPC::Europe 2nd August 2010 125 Recommended Book The Definitive Guide to Catalyst – Kieren Diment – Matt S Trout
126
PSGI/Plack
127
YAPC::Europe 2nd August 2010 127 PSGI/Plack “PSGI is an interface between Perl web applications and web servers, and Plack is a Perl module and toolkit that contains PSGI middleware, helpers and adapters to web servers.” – http://plackperl.org/
128
YAPC::Europe 2nd August 2010 128 PSGI/Plack PSGI is a specification (based on Python's WSGI) Plack is a reference implementation (based on Ruby's Rack)
129
YAPC::Europe 2nd August 2010 129 The Problem There are many ways to write web applications There are many ways to write web applications in Perl Each is subtly different Hard to move an application between server architectures
130
YAPC::Europe 2nd August 2010 130 Server Architectures CGI FastCGI mod_perl etc...
131
YAPC::Europe 2nd August 2010 131 Frameworks There are many Perl web application frameworks Each creates applications in subtly different ways Hard to port applications between them
132
YAPC::Europe 2nd August 2010 132 The Goal What if we had a specification that allowed us to easily move web applications between server architectures and frameworks PSGI is that specification
133
YAPC::Europe 2nd August 2010 133 PSGI Application my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
134
YAPC::Europe 2nd August 2010 134 PSGI Application A code reference Passed a reference to an environment hash Returns a reference to a three-element array – Status code – Headers – Body
135
YAPC::Europe 2nd August 2010 135 A Code Reference my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
136
YAPC::Europe 2nd August 2010 136 A Code Reference my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
137
YAPC::Europe 2nd August 2010 137 Environment Hash my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
138
YAPC::Europe 2nd August 2010 138 Environment Hash my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
139
YAPC::Europe 2nd August 2010 139 Return Array Ref my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
140
YAPC::Europe 2nd August 2010 140 Return Array Ref my $app = sub { my $env = shift; return [ 200, [ ‘Content-Type’, ‘text/plain’ ], [ ‘Hello World’ ], ]; };
141
YAPC::Europe 2nd August 2010 141 Running PSGI App Put code in app.psgi Drop in into a configured PSGI-aware web server Browse to URL
142
YAPC::Europe 2nd August 2010 142 PSGI-Aware Server Plack contains a simple test server called plackup $ plackup app.psgi HTTP::Server::PSGI: Accepting connections at http://localhost:5000/
143
YAPC::Europe 2nd August 2010 143 Plack::Request Plack::Request turns the environment into a request object use Plack::Request; use Data::Dumper; my $app = sub { my $req = Plack::Request->new(shift); return [ 200, [ 'Content-type', 'text/plain' ], [ Dumper $req ], ]; }
144
YAPC::Europe 2nd August 2010 144 Plack::Response Plack::Response builds a PSGI response object use Plack::Request; use Plack::Response; use Data::Dumper; my $app = sub { my $req = Plack::Request->new(shift); my $res = Plack::Response->new(200); $res->content_type('text/plain'); $res->body(Dumper $req); return $res->finalize; }
145
YAPC::Europe 2nd August 2010 145 Middleware Middleware wraps around an application Returns another PSGI application Simple spec makes this easy Plack::Middleware::* Plack::Builder adds middleware configuration language
146
YAPC::Europe 2nd August 2010 146 Middleware Example use Plack::Builder; use Plack::Middleware::Runtime; my $app = sub { my $env = shift; return [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world' ], ] }; builder { enable 'Runtime'; $app; }
147
YAPC::Europe 2nd August 2010 147 Middleware Example $ HEAD http://localhost:5000 200 OK Date: Tue, 20 Jul 2010 20:25:52 GMT Server: HTTP::Server::PSGI Content-Length: 11 Content-Type: text/plain Client-Date: Tue, 20 Jul 2010 20:25:52 GMT Client-Peer: 127.0.0.1:5000 Client-Response-Num: 1 X-Runtime: 0.000050
148
YAPC::Europe 2nd August 2010 148 Middleware Example $ HEAD http://localhost:5000 200 OK Date: Tue, 20 Jul 2010 20:25:52 GMT Server: HTTP::Server::PSGI Content-Length: 11 Content-Type: text/plain Client-Date: Tue, 20 Jul 2010 20:25:52 GMT Client-Peer: 127.0.0.1:5000 Client-Response-Num: 1 X-Runtime: 0.000050
149
YAPC::Europe 2nd August 2010 149 Plack::App::* Ready-made solutions for common situations Plack::App::CGIBin – Cgi-bin replacement Plack::App::Directory – Serve files with directory index Plack::App::URLMap – Map apps to different paths
150
YAPC::Europe 2nd August 2010 150 Plack::App::* Many more bundled with Plack Configured using Plack::Builder
151
YAPC::Europe 2nd August 2010 151 Plack::App::CGIBin use Plack::App::CGIBin; use Plack::Builder; my $app = Plack::App::CGIBin->new( root => '/var/www/cgi-bin' )->to_app; builder { mount '/cgi-bin' => $app; };
152
YAPC::Europe 2nd August 2010 152 Plack::App::Directory use Plack::App::Directory; my $app = Plack::App::Directory->new( root => '/home/dave/Dropbox/psgi' )->to_app;
153
YAPC::Europe 2nd August 2010 153 Framework Support Many modern Perl applications already support PSGI Catalyst, CGI::Application, Dancer, Jifty, Mason, Maypole, Mojolicious, Squatting, Web::Simple Many more
154
YAPC::Europe 2nd August 2010 154 Catalyst Support Catalyst::Engine::PSGI use MyApp; MyApp->setup_engine('PSGI'); my $app = sub { MyApp->run(@_) }; Also Catalyst::Helper::PSGI script/myapp_create.pl PSGI
155
YAPC::Europe 2nd August 2010 155 PSGI Server Support Many new web servers support PSGI Starman, Starlet, Twiggy, Corona, HTTP::Server::Simple::PSGI Perlbal::Plugin::PSGI
156
YAPC::Europe 2nd August 2010 156 PSGI Server Support nginx support mod_psgi Plack::Handler::Apache2
157
YAPC::Europe 2nd August 2010 157 Plack::Handler::Apache2 SetHandler perl-script PerlResponseHandler Plack::Handler::Apache2 PerlSetVar psgi_app /path/to/app.psgi
158
YAPC::Europe 2nd August 2010 158 PSGI/Plack Summary PSGI is a specification Plack is an implementation PSGI makes your life easier Most of the frameworks and server you use already support PSGI No excuse not to use it
159
YAPC::Europe 2nd August 2010 159 Further Information perldoc PSGI perldoc Plack http://plackperl.org/ http://blog.plackperl.org/ http://github.com/miyagawa/Plack #plack on irc.perl.org
160
YAPC::Europe 2nd August 2010 160 Modern Perl Summary Perl has changed a lot in the last five years Perl continues to grow and change Perl is not a “scripting language” Perl is a powerful and flexible programming language Perl is a great way to get your job done
161
That's all folks Any questions?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.