Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Mojolicious - A new hope

16,699 views

Published on

My presentation of the Mojolicious framework for London Perl Workshop 2010.

Published in: Technology
  • Be the first to comment

Mojolicious - A new hope

  1. 1. moJoLicIoUSA new hope.
  2. 2. I am MarcusI work here:
  3. 3. Nordaaker Consulting
  4. 4. But we’re moving south in january:
  5. 5. Be sure to visit!
  6. 6. perl -Mojo -eg("www.bbc.co.uk")->dom("#news_container a")->each(sub { b(shift->text) ->encode("UTF-8")->say})
  7. 7. Actually, it didn’thappen just like that.
  8. 8. Sebastian Riedel @kraih
  9. 9. Took over Maypole. Wanted to make radical changes
  10. 10. GotBooted
  11. 11. Created Catalyst.Wanted to make radical changes
  12. 12. GotBooted
  13. 13. mojolicious.org
  14. 14. Wanted to targetPHP developers & Perl 6
  15. 15. Ease of install/porting ➜ Only Perl5 core dependencies
  16. 16. • $ curl -L cpanmin.us | perl - Mojolicious Fetching http://search.cpan.org/CPAN/authors/id/K/KR/ KRAIH/Mojolicious-0.999950.tar.gz ... OK Configuring Mojolicious-0.999950 ... OK Building and testing Mojolicious-0.999950 for Mojolicious ... OK Successfully installed Mojolicious-0.999950• Gratuitous App::cpanminus plug :)
  17. 17. Latest from github:curl -L cpanmin.us | perl - http:// lastest.mojolicio.us
  18. 18. A fullHTTP 1.1compliant stack
  19. 19. Mojo::TransactionMojo::Message::Response Mojo::Cookie Mojo::URL +++
  20. 20. Test DrivenDevelopment
  21. 21. RFC DrivenDevelopment
  22. 22. PRAGMATIC
  23. 23. Next logical step:Add a client on top of this stack.
  24. 24. Supports IPV6,TLS,proxies, epoll, kqueue
  25. 25. Mojo == LegoBuilt from reusable bricks.
  26. 26. Parallelrequests
  27. 27. my $callback = sub { print shift−>res−>body};$client−>get(http://mojolicious.org => $callback);$client−>get(http://search.cpan.org => $callback);$client−>start;
  28. 28. Form Handling
  29. 29. # Form post with exception handlingmy $cpan = http://search.cpan.org/search;my $search = {q => mojo};my $tx = $client−>post_form($cpan => $search);if (my $res = $tx−>success) { print $res−>body} else { my ($message, $code) = $tx−>error; print "Error: $message";}
  30. 30. Oneliners Photo by http://www.flickr.com/photos/st3f4n/3951143570/
  31. 31. Collection of single letter commands.
  32. 32. g ➜ get d ➜ deletef ➜ form post p ➜ post u ➜ putw ➜ websocket
  33. 33. Special Casesb ➜ byte stream, a ➜ Lite app
  34. 34. #ojo modulemy $res = g( http://mojolicio.us, {Content−Type => text/plain}, Hello! );perl -Mojo -e b(g("mojolicio.us")->dom->at("title")->text)->sayperl -Mojo -Eg("bloomberg.com")->dom("a.story_link")->each(sub { sayshift->text; })perl -Mojo -Eg("digg.com")->dom("a.story-title")->each(sub { say pop, ". ",shift->text })# Undocumented -Ofun Mojolicious cloud function:perl -Mojo -e oO("http://www.reddit.com")->dom->find("a.title")->each(sub { Oo(pop . ". " . shift->text)->say })
  35. 35. Mojo::DOM
  36. 36. Liberal XML Parser
  37. 37. Supports all CSS3 selectors that make sense
  38. 38. * E[foo=”bar”] E:checked E:empty E:nth-childE:first-of-type E:not(s) EF E>F ++++
  39. 39. -Ofun If you needperformance use libXML
  40. 40. DEBUG MODE:MOJO_CLIENT_DEBUG=1 perl -Mojo -E’...’
  41. 41. # Streaming responsemy $tx = $client−>build_tx(GET => http://mojolicious.org);$tx−>res−>body(sub { print $_[1] });$client−>start($tx);# Custom socketmy $tx = $client−>build_tx(GET => http://mojolicious.org);$tx−>connection($socket);$client−>start($tx);
  42. 42. Big Body Just Works
  43. 43. $res->jsonAutomatic JSONdeserialization
  44. 44. WEBSOCKET REVOLUTION!•HTML5 protocol for long running processes•Mojo first Perl framework to add support•perl -MMojolicious::Lite -e "websocket / => sub {shift->receive_message(sub { shift- >send_message(shift)})}; shagadelic daemon"•github.com/vti - web socket goodness•Suppports latest revision of the spec.
  45. 45. $client−>websocket(ws://websockets.org:8787 =>sub { my $client = shift; $client−>on_message( sub { my ($client, $message) = @_; print "$messagen"; $client−>finish; }); $client−>send_message(hiya!);})−>start;
  46. 46. Browser Support messy. Politics.
  47. 47. Use the Flash Fallback.
  48. 48. Mojolicious MVC
  49. 49. $ mojo generate lite_app tinyws [exist] /Users/marcus [write] /Users/marcus/tinyws [chmod] tinyws 744• That was easy. Now let’s check out the contents of the file
  50. 50. #!/usr/bin/env perluse Mojolicious::Lite;get / => index;get /:groovy => sub { my $self = shift; $self->render_text( $self->param(groovy));};app->start;
  51. 51. __DATA__@@ index.html.ep% layout funky;Yea baby!@@ layouts/funky.html.ep<!doctype html><html> <head><title>Funky!</title></head> <body><%== content %></body></html>
  52. 52. % ./tinywsusage: ./tinyws COMMAND [OPTIONS]Tip: CGI, FastCGI and PSGI environments can be automatically detected very often and work without commands.These commands are currently available: cgi Start application with CGI. daemon Start application with HTTP 1.1 and WebSocket server. fastcgi Start application with FastCGI. generate Generate files and directories from templates. get Get file from URL. hypnotoad Start application with Hypnotoad. inflate Inflate embedded files to real files. psgi Start application with PSGI. routes Show available routes. test Run unit tests. version Show versions of installed modules. daemon_prefork Start application with preforking HTTP 1.1 backend.These options are available for all commands: --home <path> Path to your applications home directory, defaults to the value of MOJO_HOME or auto detection. --mode <name> Run mode of your application, defaults to the value of MOJO_MODE or development.See ./tinyws help COMMAND for more information on a specific command.
  53. 53. Handles 3 different urls• /• /*• /*/*
  54. 54. # ::Liteget ‘/’ => ‘index’;# sub refs for functionspost ‘/login’ => sub { .. };# Placeholders & Actions:get ‘/:foo’ => sub {},‘ctrl’# All togetherget /everything/:stuff => [stuff => qr/d+/]=> {stuff => 23} =>sub { shift->render(welcome); }
  55. 55. ladder sub { my $self = shift # Authenticated my $name = $self->param(name) || ; return 1 if $name eq Bender; # Not authenticated $self->render(denied); return;}
  56. 56. $ mojo generate app tinyws2 [write] /Users/marcus/tinyws2/script/tinyws2 [write] /Users/marcus/tinyws2/lib/tinyws2.pm [write] /Users/marcus/tinyws2/lib/tinyws2/Example.pm [write] /Users/marcus/tinyws2/t/basic.t [write] /Users/marcus/tinyws2/public/index.html [write] /Users/marcus/tinyws2/templates/not_found.html.ep [write] /Users/marcus/tinyws2/templates/exception.html.ep [write] /Users/marcus/tinyws2/templates/layouts/default.html.ep [write] /Users/marcus/tinyws2/templates/example/welcome.html.epSnipped out all the mkdir/chmod for brevity.
  57. 57. $r->route(‘/’)->to (controller=>‘foo’,action=> ‘bar’); (lists#new, id => 1)->name(new); (/:controller/:action/:id)->to (example#welcome, id => 1)# Bridgesmy $auth=$r->bridge->to(‘auth#check’);$auth->route(...)
  58. 58. Mojo::Template
  59. 59. % my $player=$self->stash(‘players’);%= $player; # print%== $player; # raw<%= player %> <%== player %> # inline style% # Normal comment<% # inline comment %>.ep - prepopulates stash for you.epl - same templates, less magic
  60. 60. MojoX::Renderer::TT
  61. 61. MojoX::Renderer::Mason
  62. 62. MojoX::Renderer::XSLT
  63. 63. MojoX::Renderer::Xslate
  64. 64. MojoX::Renderer::CTPP2
  65. 65. MojoX::Renderer::YAML
  66. 66. default helpersdumperparamstashlayoutincludecontentextendsurl_for
  67. 67. ->render->render(template=>‘foo/bar’)->render(controller=>‘foo’,action=>‘bar’)->render(‘foo#bar’)->render_text->render_json->render_inner->render_partial->pause / ->resume->redirect_to / ->url_for
  68. 68. PLUGINS
  69. 69. Hook basedbefore_dispatchafter_dispatchafter_static_dispatchafter_build_txAlso apropriate place to add types & renders &custom routes extension.
  70. 70. Mojolicious::Plugin::AgentCondition - Agent Condition  Mojolicious::Plugin::Charset - Default Charset  Mojolicious::Plugin::DefaultHelpers - Default Helpers  Mojolicious::Plugin::EpRenderer - EP Renderer  Mojolicious::Plugin::EplRenderer -EPL Renderer Mojolicious::Plugin::HeaderCondition - Header Condition Mojolicious::Plugin::I18n Internationalization Plugin  Mojolicious::Plugin::JsonConfig - JSON Configuration Mojolicious::Plugin::PodRenderer - POD Renderer Mojolicious::Plugin::PoweredBy - Powered By Plugin   Mojolicious::Plugin::RequestTimer - Time requests
  71. 71. PSGI supportedout of the box
  72. 72. All glory to the Hypnotoad•Production ready standalone server•Hot deployment using unix signals•Set up Worker threads, pid file, reverse proxy support through a simple config file•Web Socket support.
  73. 73. $ mojo generate hypnotoad[exists] /myapp/[write] /myapp/hypnotoad.conf
  74. 74. { listen => [http://*:8080], workers => 4};
  75. 75. Server:"INT", "TERM"Shutdown server"QUIT" Shutdown server gracefully"TTIN" Increase worker pool by one"TTOU" Decrease worker pool by one"USR2" hot deployment.Worker:"INT", "TERM"Shutdown server"QUIT" Shutdown server gracefully
  76. 76. $ perldoc Mojo::Server::Hypnotoad
  77. 77. Community
  78. 78. Big in Russia
  79. 79. Growing in Japan
  80. 80. -Ofun Every file in the distro has a Simpsons orFuturama quote.
  81. 81. Test DrivenDevelopment
  82. 82. Youprovidefailingtest - srifixes
  83. 83. 1.0 expected by christmas
  84. 84. this christmas
  85. 85. Learn More: Mojolicious::Guides mojolicious.org github.com/kraih/mojogroups.google.com/group/mojolicious
  86. 86. #mojo onirc.perl.org

×