SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
Catalyst, DBIC, and TT for
    world domination
My Background

• Lazy (Programmer)
• Often involved in sys admin (repetitive)
  work
• Leverage CPAN so I don’t have to figure
  things out others already have (Lazy)
Scripts to:
              In the beginning...

       • automate maintenance
       • systems checks, report by email.
       • check status of various processes/disk/
          memory
       • automate user tasks
Scripts to:
              In the beginning...


       • automate maintenance
        • Job failures difficult to detect
In the beginning...
Scripts to:



       • systems checks, report by email
        • Inbox flooded.
        • Still have to read and process them
        • Follow ups often require system access
Scripts to:
              In the beginning...

       • check status of various processes/disk/
          memory ($> appname_health.pl)
         • often requires privileged access
         • output in fixed font
Scripts to:
              In the beginning...


       • automate user tasks (mkuser, unlock
          account, etc)
         • user at least has to have a login
DBI + CGI
CGI - Benefits

• Accessible to anyone with a web browser
• Programs easy to deploy
• No need to login to host
CGI - Bad habits

• Accessible to anyone with a web browser
• Perl compile cost every page hit
• Long running processes not easily possible
• HTML Code mixed in with perl code
  (HERE or qw{})       print q{<HTML>
                       hello world
                       </HTML>
                       };
DBI - Benefits


• Standardized access to back end data
• Database not perl process does hard query
  work
DBI - Bad habits
•   Vulnerable to SQL injection
•   Perl code is hard coded to a specific DB type
    (MySQL, Postgres, Oracle, Sybase, MSSQL)
•   Redundant prep/execute/extract code usually
    splashed all over the code
•   Detection of errors usually not standardized
•   SQL code (often many lines long) intermixed with
    perl code. (Hard to read)
•   Badly formed SQL can reveal sensitive information
    to end user
DBI - Bad habits
•   Vulnerable to SQL injection
    •   select * foo where bar = “$test”
    •   $test = q{5; insert into admin_table...};
    •   $test = q{“blah}
    •   Difficult to handle BLOB data
•   Placeholders limited
    •   where of select, set of update, values for insert)
    •   From clause inaccessible via placeholders
DBI + CGI
Catalyst, DBIx::Class,
          TT
The Learning Curve
•   Moose!
•   DBIx::Class
•   TT
•   Catalyst
•   Model/View/Controller paradigm a difficult balance to maintain
•   Perl Testing techniques in Catalyst
    •   Catalyst unit testing (how do I exclude the models in the
        test?)
    •   Model testing (build a test DB complicated enough to test
        the model)
    •   Selenium (minor changes in TT easily break tests)
Moose
• Easy to learn for if you’ve done OO
  programming before
• http://search.cpan.org/perldoc?
  Moose::Cookbook
• No more new!?!?
• Not critical to learn but useful when
  thinking about how Catalyst works
DBIx::Class
   • Best way to call SQL but read like perl
   • Standard interface to returning query from sub
my $rs = $schema->resultset(‘CD’)
                   ->search({ year => 2000 },
                               { prefetch => 'artist' });
while ($rs->next) {
  print $rs->artist . “n”;
}
                    my $dbi = DBI->connect(...) or die DBI->error;
                    my $query = q{select artist from CD where year = 2000};
                    my $sth = $dbi->prepare($query) or die;
                    $sth->execute or die;
                    while(my ($artist) = $sth->fetchrow_array) {
                       print “$artistn”;
                    }
DBIx::Class table setup
•   Schema Loader Magic! (unless it’s not a well
    built Schema)
•   Make sure fkeys,pkeys setup in db first if you
    can.
•   Not all Pg features pull from schema loader
•   DBIx::Class::Schema::Loader to load schema
•   Alternatively: cd ~catapp; script/create.pl model
    CatalystModelName...
DBIx::Class - Caveats
•   wrap insert/updates in eval {} or x; blocks
•   txn_do($code_ref) (still inside eval block)
•   left outer joins by default. (null rows removed)
•   Understand when a query is a row or a result set.
    They behave differently.
•   inflate/deflate only works on rows, not $rs
•   relation columns can have same name as variables.
    causes you to have to do $row->get_column
Learning TT

• Think Cool PHP (if it was perl)
•   http://template-toolkit.org/docs/manual/

•   Syntax differences can be subtle and TIMTOWTDI

• Catalyst will do all the heavy lifting here.
• Mailing list is very friendly.
TT: Advice from the
         trenches
•   “Spend a solid day or more dedicated to learning Template::Toolkit. Andy Wardley has
    done an amazing job at creating and maintaining this system. By spending a little time
    up front, it will save you a TON of time in the future and get you familiar with its
    capabilities. Learn how to make it sort arrays, sort hash keys, loop through keys of
    hashes, etc - things that are vital to the template development for web applications.”

•   TT manual can be confusing to the beginner.

    •   “some basic concepts were buried in the middle of examples of various features,
        so I had to read about almost everything before I could do more than the trivial.”

    •   “I felt the TT language had too many syntactic variations for accomplishing the
        same thing, and again the examples randomly chose which version they used in
        order to demonstrate this breadth, but until you get to the part which explains
        the equivalences, you are left scratching your head trying to figure out what the
        semantic differences are.”

    •   “Aside from that, TT seems to be a powerful, stable templating system.”
TT - Trenches II


•   Case matters: [% FOR foo IN chairs.keys.sort %]

•   Prevent line wrap: [% author -%]

•   Altering the stash is local (sometimes): [% foo = ‘HELP’ %]
Learning Catalyst
   (are we there yet?)
• CPAN Tutorial
• Catalyst Examples from SVN
• Catalyst Advent Calendar
• Johnathan Rockway’s Book “Catalyst”
• Initial setup is 90% of the battle
 • catalyst.pl AppName
Cost Justification for
     the learning Curve
•   Multi-developer approach easier when code is broken into
    multiple modules
•   Automated testing setup for you
•   Stupid DBI mistakes no longer a risk (Now it’s stupid DBIC
    mistakes but they fail more consistently)
•   DB Structure separated from code in one place.
•   Annoying HTML page setup for each CGI script centralized
•   Model structure allows for easy re-use outside of Catalyst
•   Application portable to multiple developers with self
    contained web server.
MVC


• Spend time thinking about and talking about
    the demarcation for MVC
•   http://en.wikipedia.org/wiki/Model-view-controller
View
• What presents the data to the user
 • email
 • HTML
 • JSON
 • file download
 • csv
Controllers
•   Air traffic control of the application
•   Receives user input
•   Authenticates and authorizes access with help of
    models
•   Requests information from models based on user input
•   Data cleansing of user input
•   Formats data (input and output) to present back to
    view for display
Models
•   Library of calls for controllers and outside programs to:
    Query/update/insert information by:
    •   Invoking programs
    •   Accessing databases
    •   Messaging (email, IM)
•   Maintains Data integrity where pkey/fkeys stop.
•   Enforces authorization based on controllers provided
    credentials
•   Centralizes auditing of events
Lessons learned from
 Controller Development
• Do all authentication and authorization in
  root.pm via auto (Private)
• Take care not to do view or model work in
  the controllers. This is the easiest place to
  do too much
• Common Controller routines or repetitive
  code sections indicates you have a model
  routine
Lessons learned from
        Model Development
•   Pod EVERYTHING. It takes a very short time to forget
    what it does or why it’s there or how to use it.
•   Inheritance is probably not the right solution - Use Moose
    Roles instead to separate the sections of your models for
    better management
•   Models provided us a way to standardize back end
    interface to on-boarding.
•   Create a common library to validate hash passed to model
    •   my $params = validate_hash(shift, qw/date_inserted id
        owner on_hold/) or return toss(“reason...”);
Is it a model or
     controller job?

• Whether you agree with all of this
  doesn’t matter. What matters is you
  become aware of the coding issues and
  decide which way you’re going to go.
Model test suite
•   Can be difficult to create test databases
    complicated enough to validate functionality
    or replicate errors.
•   Clear /re-build database between tests
•   input/output can be complex. Build helper to
    make life easier (test_model_func({model=>..,
    func => ..., args => ...., toss =>...,}))
•   Controller bugs require a test to fix in model
Apache + FastCGI
• Allows app to be scalable.
• Multiple perl engines can run in the back end
• Engines can be on external hosts
• Scales down connections on idle
• Remember [% c->uri_for(‘/’) %] in all your
  templates
  • Catalyst::View::TT->CATALYST_VAR
In the end

• Splitting up areas of responsibility between
  controllers and models helps enforce:
  • documentation
  • interface standards
  • testing

Weitere ähnliche Inhalte

Was ist angesagt?

Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Anton Arhipov
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
Anton Arhipov
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
Vinay H G
 

Was ist angesagt? (20)

Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Scala profiling
Scala profilingScala profiling
Scala profiling
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it Fast
 
Software Development with Open Source
Software Development with Open SourceSoftware Development with Open Source
Software Development with Open Source
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012Burp Plugin Development for Java n00bs - 44CON 2012
Burp Plugin Development for Java n00bs - 44CON 2012
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
Connect 2014 JMP101: Java for XPages Development
Connect 2014 JMP101: Java for XPages DevelopmentConnect 2014 JMP101: Java for XPages Development
Connect 2014 JMP101: Java for XPages Development
 
Introduction to CouchDB
Introduction to CouchDBIntroduction to CouchDB
Introduction to CouchDB
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
 
What's the "right" PHP Framework?
What's the "right" PHP Framework?What's the "right" PHP Framework?
What's the "right" PHP Framework?
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 

Ähnlich wie Yapc10 Cdt World Domination

Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupal
Ronan Berder
 
5 Common Mistakes You are Making on your Website
 5 Common Mistakes You are Making on your Website 5 Common Mistakes You are Making on your Website
5 Common Mistakes You are Making on your Website
Acquia
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
Drupalcon Paris
 

Ähnlich wie Yapc10 Cdt World Domination (20)

Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
presentation
presentationpresentation
presentation
 
presentation
presentationpresentation
presentation
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Configuration Management in the Cloud - Cloud Phoenix Meetup Feb 2014
Configuration Management in the Cloud - Cloud Phoenix Meetup Feb 2014Configuration Management in the Cloud - Cloud Phoenix Meetup Feb 2014
Configuration Management in the Cloud - Cloud Phoenix Meetup Feb 2014
 
My first powershell script
My first powershell scriptMy first powershell script
My first powershell script
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 
Best Practices for WordPress
Best Practices for WordPressBest Practices for WordPress
Best Practices for WordPress
 
PowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue KidPowerShell - Be A Cool Blue Kid
PowerShell - Be A Cool Blue Kid
 
Performance and scalability with drupal
Performance and scalability with drupalPerformance and scalability with drupal
Performance and scalability with drupal
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
5 Common Mistakes You are Making on your Website
 5 Common Mistakes You are Making on your Website 5 Common Mistakes You are Making on your Website
5 Common Mistakes You are Making on your Website
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 
Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3Staging Drupal 8 31 09 1 3
Staging Drupal 8 31 09 1 3
 
Why ruby and rails
Why ruby and railsWhy ruby and rails
Why ruby and rails
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
Standardizing and Managing Your Infrastructure - MOSC 2011
Standardizing and Managing Your Infrastructure - MOSC 2011Standardizing and Managing Your Infrastructure - MOSC 2011
Standardizing and Managing Your Infrastructure - MOSC 2011
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Yapc10 Cdt World Domination

  • 1. Catalyst, DBIC, and TT for world domination
  • 2. My Background • Lazy (Programmer) • Often involved in sys admin (repetitive) work • Leverage CPAN so I don’t have to figure things out others already have (Lazy)
  • 3. Scripts to: In the beginning... • automate maintenance • systems checks, report by email. • check status of various processes/disk/ memory • automate user tasks
  • 4. Scripts to: In the beginning... • automate maintenance • Job failures difficult to detect
  • 5. In the beginning... Scripts to: • systems checks, report by email • Inbox flooded. • Still have to read and process them • Follow ups often require system access
  • 6. Scripts to: In the beginning... • check status of various processes/disk/ memory ($> appname_health.pl) • often requires privileged access • output in fixed font
  • 7. Scripts to: In the beginning... • automate user tasks (mkuser, unlock account, etc) • user at least has to have a login
  • 9. CGI - Benefits • Accessible to anyone with a web browser • Programs easy to deploy • No need to login to host
  • 10. CGI - Bad habits • Accessible to anyone with a web browser • Perl compile cost every page hit • Long running processes not easily possible • HTML Code mixed in with perl code (HERE or qw{}) print q{<HTML> hello world </HTML> };
  • 11. DBI - Benefits • Standardized access to back end data • Database not perl process does hard query work
  • 12. DBI - Bad habits • Vulnerable to SQL injection • Perl code is hard coded to a specific DB type (MySQL, Postgres, Oracle, Sybase, MSSQL) • Redundant prep/execute/extract code usually splashed all over the code • Detection of errors usually not standardized • SQL code (often many lines long) intermixed with perl code. (Hard to read) • Badly formed SQL can reveal sensitive information to end user
  • 13. DBI - Bad habits • Vulnerable to SQL injection • select * foo where bar = “$test” • $test = q{5; insert into admin_table...}; • $test = q{“blah} • Difficult to handle BLOB data • Placeholders limited • where of select, set of update, values for insert) • From clause inaccessible via placeholders
  • 16. The Learning Curve • Moose! • DBIx::Class • TT • Catalyst • Model/View/Controller paradigm a difficult balance to maintain • Perl Testing techniques in Catalyst • Catalyst unit testing (how do I exclude the models in the test?) • Model testing (build a test DB complicated enough to test the model) • Selenium (minor changes in TT easily break tests)
  • 17. Moose • Easy to learn for if you’ve done OO programming before • http://search.cpan.org/perldoc? Moose::Cookbook • No more new!?!? • Not critical to learn but useful when thinking about how Catalyst works
  • 18. DBIx::Class • Best way to call SQL but read like perl • Standard interface to returning query from sub my $rs = $schema->resultset(‘CD’) ->search({ year => 2000 }, { prefetch => 'artist' }); while ($rs->next) { print $rs->artist . “n”; } my $dbi = DBI->connect(...) or die DBI->error; my $query = q{select artist from CD where year = 2000}; my $sth = $dbi->prepare($query) or die; $sth->execute or die; while(my ($artist) = $sth->fetchrow_array) { print “$artistn”; }
  • 19. DBIx::Class table setup • Schema Loader Magic! (unless it’s not a well built Schema) • Make sure fkeys,pkeys setup in db first if you can. • Not all Pg features pull from schema loader • DBIx::Class::Schema::Loader to load schema • Alternatively: cd ~catapp; script/create.pl model CatalystModelName...
  • 20. DBIx::Class - Caveats • wrap insert/updates in eval {} or x; blocks • txn_do($code_ref) (still inside eval block) • left outer joins by default. (null rows removed) • Understand when a query is a row or a result set. They behave differently. • inflate/deflate only works on rows, not $rs • relation columns can have same name as variables. causes you to have to do $row->get_column
  • 21. Learning TT • Think Cool PHP (if it was perl) • http://template-toolkit.org/docs/manual/ • Syntax differences can be subtle and TIMTOWTDI • Catalyst will do all the heavy lifting here. • Mailing list is very friendly.
  • 22. TT: Advice from the trenches • “Spend a solid day or more dedicated to learning Template::Toolkit. Andy Wardley has done an amazing job at creating and maintaining this system. By spending a little time up front, it will save you a TON of time in the future and get you familiar with its capabilities. Learn how to make it sort arrays, sort hash keys, loop through keys of hashes, etc - things that are vital to the template development for web applications.” • TT manual can be confusing to the beginner. • “some basic concepts were buried in the middle of examples of various features, so I had to read about almost everything before I could do more than the trivial.” • “I felt the TT language had too many syntactic variations for accomplishing the same thing, and again the examples randomly chose which version they used in order to demonstrate this breadth, but until you get to the part which explains the equivalences, you are left scratching your head trying to figure out what the semantic differences are.” • “Aside from that, TT seems to be a powerful, stable templating system.”
  • 23. TT - Trenches II • Case matters: [% FOR foo IN chairs.keys.sort %] • Prevent line wrap: [% author -%] • Altering the stash is local (sometimes): [% foo = ‘HELP’ %]
  • 24. Learning Catalyst (are we there yet?) • CPAN Tutorial • Catalyst Examples from SVN • Catalyst Advent Calendar • Johnathan Rockway’s Book “Catalyst” • Initial setup is 90% of the battle • catalyst.pl AppName
  • 25. Cost Justification for the learning Curve • Multi-developer approach easier when code is broken into multiple modules • Automated testing setup for you • Stupid DBI mistakes no longer a risk (Now it’s stupid DBIC mistakes but they fail more consistently) • DB Structure separated from code in one place. • Annoying HTML page setup for each CGI script centralized • Model structure allows for easy re-use outside of Catalyst • Application portable to multiple developers with self contained web server.
  • 26. MVC • Spend time thinking about and talking about the demarcation for MVC • http://en.wikipedia.org/wiki/Model-view-controller
  • 27. View • What presents the data to the user • email • HTML • JSON • file download • csv
  • 28. Controllers • Air traffic control of the application • Receives user input • Authenticates and authorizes access with help of models • Requests information from models based on user input • Data cleansing of user input • Formats data (input and output) to present back to view for display
  • 29. Models • Library of calls for controllers and outside programs to: Query/update/insert information by: • Invoking programs • Accessing databases • Messaging (email, IM) • Maintains Data integrity where pkey/fkeys stop. • Enforces authorization based on controllers provided credentials • Centralizes auditing of events
  • 30. Lessons learned from Controller Development • Do all authentication and authorization in root.pm via auto (Private) • Take care not to do view or model work in the controllers. This is the easiest place to do too much • Common Controller routines or repetitive code sections indicates you have a model routine
  • 31. Lessons learned from Model Development • Pod EVERYTHING. It takes a very short time to forget what it does or why it’s there or how to use it. • Inheritance is probably not the right solution - Use Moose Roles instead to separate the sections of your models for better management • Models provided us a way to standardize back end interface to on-boarding. • Create a common library to validate hash passed to model • my $params = validate_hash(shift, qw/date_inserted id owner on_hold/) or return toss(“reason...”);
  • 32. Is it a model or controller job? • Whether you agree with all of this doesn’t matter. What matters is you become aware of the coding issues and decide which way you’re going to go.
  • 33. Model test suite • Can be difficult to create test databases complicated enough to validate functionality or replicate errors. • Clear /re-build database between tests • input/output can be complex. Build helper to make life easier (test_model_func({model=>.., func => ..., args => ...., toss =>...,})) • Controller bugs require a test to fix in model
  • 34. Apache + FastCGI • Allows app to be scalable. • Multiple perl engines can run in the back end • Engines can be on external hosts • Scales down connections on idle • Remember [% c->uri_for(‘/’) %] in all your templates • Catalyst::View::TT->CATALYST_VAR
  • 35. In the end • Splitting up areas of responsibility between controllers and models helps enforce: • documentation • interface standards • testing