1Mojolicious(3) User Contributed Perl Documentation Mojolicious(3)
2
3
4
6 Mojolicious - Real-time web framework
7
9 # Application
10 package MyApp;
11 use Mojo::Base 'Mojolicious';
12
13 # Route
14 sub startup {
15 my $self = shift;
16 $self->routes->get('/hello')->to('foo#hello');
17 }
18
19 # Controller
20 package MyApp::Controller::Foo;
21 use Mojo::Base 'Mojolicious::Controller';
22
23 # Action
24 sub hello {
25 my $self = shift;
26 $self->render(text => 'Hello World!');
27 }
28
30 An amazing real-time web framework built on top of the powerful Mojo
31 web development toolkit. With support for RESTful routes, plugins,
32 commands, Perl-ish templates, content negotiation, session management,
33 form validation, testing framework, static file server, "CGI"/"PSGI"
34 detection, first class Unicode support and much more for you to
35 discover.
36
37 Take a look at our excellent documentation in Mojolicious::Guides!
38
40 Mojolicious will emit the following hooks in the listed order.
41
42 before_server_start
43 Emitted right before the application server is started, for web servers
44 that support it, which includes all the built-in ones (except for
45 Mojo::Server::CGI).
46
47 $app->hook(before_server_start => sub {
48 my ($server, $app) = @_;
49 ...
50 });
51
52 Useful for reconfiguring application servers dynamically or collecting
53 server diagnostics information. (Passed the server and application
54 objects)
55
56 after_build_tx
57 Emitted right after the transaction is built and before the HTTP
58 request gets parsed.
59
60 $app->hook(after_build_tx => sub {
61 my ($tx, $app) = @_;
62 ...
63 });
64
65 This is a very powerful hook and should not be used lightly, it makes
66 some rather advanced features such as upload progress bars possible.
67 Note that this hook will not work for embedded applications, because
68 only the host application gets to build transactions. (Passed the
69 transaction and application objects)
70
71 around_dispatch
72 Emitted right after a new request has been received and wraps around
73 the whole dispatch process, so you have to manually forward to the next
74 hook if you want to continue the chain. Default exception handling with
75 "reply->exception" in Mojolicious::Plugin::DefaultHelpers is the first
76 hook in the chain and a call to "dispatch" the last, yours will be in
77 between.
78
79 $app->hook(around_dispatch => sub {
80 my ($next, $c) = @_;
81 ...
82 $next->();
83 ...
84 });
85
86 This is a very powerful hook and should not be used lightly, it allows
87 you to, for example, customize application-wide exception handling,
88 consider it the sledgehammer in your toolbox. (Passed a callback
89 leading to the next hook and the default controller object)
90
91 before_dispatch
92 Emitted right before the static file server and router start their
93 work.
94
95 $app->hook(before_dispatch => sub {
96 my $c = shift;
97 ...
98 });
99
100 Very useful for rewriting incoming requests and other preprocessing
101 tasks. (Passed the default controller object)
102
103 after_static
104 Emitted after a static file response has been generated by the static
105 file server.
106
107 $app->hook(after_static => sub {
108 my $c = shift;
109 ...
110 });
111
112 Mostly used for post-processing static file responses. (Passed the
113 default controller object)
114
115 before_routes
116 Emitted after the static file server determined if a static file should
117 be served and before the router starts its work.
118
119 $app->hook(before_routes => sub {
120 my $c = shift;
121 ...
122 });
123
124 Mostly used for custom dispatchers and collecting metrics. (Passed the
125 default controller object)
126
127 around_action
128 Emitted right before an action gets executed and wraps around it, so
129 you have to manually forward to the next hook if you want to continue
130 the chain. Default action dispatching is the last hook in the chain,
131 yours will run before it.
132
133 $app->hook(around_action => sub {
134 my ($next, $c, $action, $last) = @_;
135 ...
136 return $next->();
137 });
138
139 This is a very powerful hook and should not be used lightly, it allows
140 you for example to pass additional arguments to actions or handle
141 return values differently. Note that this hook can trigger more than
142 once for the same request if there are nested routes. (Passed a
143 callback leading to the next hook, the current controller object, the
144 action callback and a flag indicating if this action is an endpoint)
145
146 before_render
147 Emitted before content is generated by the renderer. Note that this
148 hook can trigger out of order due to its dynamic nature, and with
149 embedded applications will only work for the application that is
150 rendering.
151
152 $app->hook(before_render => sub {
153 my ($c, $args) = @_;
154 ...
155 });
156
157 Mostly used for pre-processing arguments passed to the renderer.
158 (Passed the current controller object and the render arguments)
159
160 after_render
161 Emitted after content has been generated by the renderer that will be
162 assigned to the response. Note that this hook can trigger out of order
163 due to its dynamic nature, and with embedded applications will only
164 work for the application that is rendering.
165
166 $app->hook(after_render => sub {
167 my ($c, $output, $format) = @_;
168 ...
169 });
170
171 Mostly used for post-processing dynamically generated content. (Passed
172 the current controller object, a reference to the content and the
173 format)
174
175 after_dispatch
176 Emitted in reverse order after a response has been generated. Note that
177 this hook can trigger out of order due to its dynamic nature, and with
178 embedded applications will only work for the application that is
179 generating the response.
180
181 $app->hook(after_dispatch => sub {
182 my $c = shift;
183 ...
184 });
185
186 Useful for rewriting outgoing responses and other post-processing
187 tasks. (Passed the current controller object)
188
190 Mojolicious implements the following attributes.
191
192 commands
193 my $commands = $app->commands;
194 $app = $app->commands(Mojolicious::Commands->new);
195
196 Command line interface for your application, defaults to a
197 Mojolicious::Commands object.
198
199 # Add another namespace to load commands from
200 push @{$app->commands->namespaces}, 'MyApp::Command';
201
202 controller_class
203 my $class = $app->controller_class;
204 $app = $app->controller_class('Mojolicious::Controller');
205
206 Class to be used for the default controller, defaults to
207 Mojolicious::Controller. Note that this class needs to have already
208 been loaded before the first request arrives.
209
210 home
211 my $home = $app->home;
212 $app = $app->home(Mojo::Home->new);
213
214 The home directory of your application, defaults to a Mojo::Home object
215 which stringifies to the actual path.
216
217 # Portably generate path relative to home directory
218 my $path = $app->home->child('data', 'important.txt');
219
220 log
221 my $log = $app->log;
222 $app = $app->log(Mojo::Log->new);
223
224 The logging layer of your application, defaults to a Mojo::Log object.
225 The level will default to either the "MOJO_LOG_LEVEL" environment
226 variable, "debug" if the "mode" is "development", or "info" otherwise.
227 All messages will be written to "STDERR", or a "log/$mode.log" file if
228 a "log" directory exists.
229
230 # Log debug message
231 $app->log->debug('It works');
232
233 max_request_size
234 my $max = $app->max_request_size;
235 $app = $app->max_request_size(16777216);
236
237 Maximum request size in bytes, defaults to the value of
238 "max_message_size" in Mojo::Message. Setting the value to 0 will allow
239 requests of indefinite size. Note that increasing this value can also
240 drastically increase memory usage, should you for example attempt to
241 parse an excessively large request body with the methods "dom" in
242 Mojo::Message or "json" in Mojo::Message.
243
244 mode
245 my $mode = $app->mode;
246 $app = $app->mode('production');
247
248 The operating mode for your application, defaults to a value from the
249 "MOJO_MODE" and "PLACK_ENV" environment variables or "development".
250
251 moniker
252 my $moniker = $app->moniker;
253 $app = $app->moniker('foo_bar');
254
255 Moniker of this application, often used as default filename for
256 configuration files and the like, defaults to decamelizing the
257 application class with "decamelize" in Mojo::Util.
258
259 plugins
260 my $plugins = $app->plugins;
261 $app = $app->plugins(Mojolicious::Plugins->new);
262
263 The plugin manager, defaults to a Mojolicious::Plugins object. See the
264 "plugin" method below if you want to load a plugin.
265
266 # Add another namespace to load plugins from
267 push @{$app->plugins->namespaces}, 'MyApp::Plugin';
268
269 renderer
270 my $renderer = $app->renderer;
271 $app = $app->renderer(Mojolicious::Renderer->new);
272
273 Used to render content, defaults to a Mojolicious::Renderer object. For
274 more information about how to generate content see
275 Mojolicious::Guides::Rendering.
276
277 # Enable compression
278 $app->renderer->compress(1);
279
280 # Add another "templates" directory
281 push @{$app->renderer->paths}, '/home/sri/templates';
282
283 # Add another "templates" directory with higher precedence
284 unshift @{$app->renderer->paths}, '/home/sri/themes/blue/templates';
285
286 # Add another class with templates in DATA section
287 push @{$app->renderer->classes}, 'Mojolicious::Plugin::Fun';
288
289 routes
290 my $routes = $app->routes;
291 $app = $app->routes(Mojolicious::Routes->new);
292
293 The router, defaults to a Mojolicious::Routes object. You use this in
294 your startup method to define the url endpoints for your application.
295
296 # Add routes
297 my $r = $app->routes;
298 $r->get('/foo/bar')->to('test#foo', title => 'Hello Mojo!');
299 $r->post('/baz')->to('test#baz');
300
301 # Add another namespace to load controllers from
302 push @{$app->routes->namespaces}, 'MyApp::MyController';
303
304 secrets
305 my $secrets = $app->secrets;
306 $app = $app->secrets([$bytes]);
307
308 Secret passphrases used for signed cookies and the like, defaults to
309 the "moniker" of this application, which is not very secure, so you
310 should change it!!! As long as you are using the insecure default there
311 will be debug messages in the log file reminding you to change your
312 passphrase. Only the first passphrase is used to create new signatures,
313 but all of them for verification. So you can increase security without
314 invalidating all your existing signed cookies by rotating passphrases,
315 just add new ones to the front and remove old ones from the back.
316
317 # Rotate passphrases
318 $app->secrets(['new_passw0rd', 'old_passw0rd', 'very_old_passw0rd']);
319
320 sessions
321 my $sessions = $app->sessions;
322 $app = $app->sessions(Mojolicious::Sessions->new);
323
324 Signed cookie based session manager, defaults to a
325 Mojolicious::Sessions object. You can usually leave this alone, see
326 "session" in Mojolicious::Controller for more information about working
327 with session data.
328
329 # Change name of cookie used for all sessions
330 $app->sessions->cookie_name('mysession');
331
332 static
333 my $static = $app->static;
334 $app = $app->static(Mojolicious::Static->new);
335
336 For serving static files from your "public" directories, defaults to a
337 Mojolicious::Static object.
338
339 # Add another "public" directory
340 push @{$app->static->paths}, '/home/sri/public';
341
342 # Add another "public" directory with higher precedence
343 unshift @{$app->static->paths}, '/home/sri/themes/blue/public';
344
345 # Add another class with static files in DATA section
346 push @{$app->static->classes}, 'Mojolicious::Plugin::Fun';
347
348 # Remove built-in favicon
349 delete $app->static->extra->{'favicon.ico'};
350
351 types
352 my $types = $app->types;
353 $app = $app->types(Mojolicious::Types->new);
354
355 Responsible for connecting file extensions with MIME types, defaults to
356 a Mojolicious::Types object.
357
358 # Add custom MIME type
359 $app->types->type(twt => 'text/tweet');
360
361 ua
362 my $ua = $app->ua;
363 $app = $app->ua(Mojo::UserAgent->new);
364
365 A full featured HTTP user agent for use in your applications, defaults
366 to a Mojo::UserAgent object.
367
368 # Perform blocking request
369 say $app->ua->get('example.com')->result->body;
370
371 validator
372 my $validator = $app->validator;
373 $app = $app->validator(Mojolicious::Validator->new);
374
375 Validate values, defaults to a Mojolicious::Validator object.
376
377 # Add validation check
378 $app->validator->add_check(foo => sub {
379 my ($v, $name, $value) = @_;
380 return $value ne 'foo';
381 });
382
383 # Add validation filter
384 $app->validator->add_filter(quotemeta => sub {
385 my ($v, $name, $value) = @_;
386 return quotemeta $value;
387 });
388
390 Mojolicious inherits all methods from Mojo::Base and implements the
391 following new ones.
392
393 build_controller
394 my $c = $app->build_controller;
395 my $c = $app->build_controller(Mojo::Transaction::HTTP->new);
396 my $c = $app->build_controller(Mojolicious::Controller->new);
397
398 Build default controller object with "controller_class".
399
400 # Render template from application
401 my $foo = $app->build_controller->render_to_string(template => 'foo');
402
403 build_tx
404 my $tx = $app->build_tx;
405
406 Build Mojo::Transaction::HTTP object and emit "after_build_tx" hook.
407
408 config
409 my $hash = $app->config;
410 my $foo = $app->config('foo');
411 $app = $app->config({foo => 'bar', baz => 23});
412 $app = $app->config(foo => 'bar', baz => 23);
413
414 Application configuration.
415
416 # Remove value
417 my $foo = delete $app->config->{foo};
418
419 # Assign multiple values at once
420 $app->config(foo => 'test', bar => 23);
421
422 defaults
423 my $hash = $app->defaults;
424 my $foo = $app->defaults('foo');
425 $app = $app->defaults({foo => 'bar', baz => 23});
426 $app = $app->defaults(foo => 'bar', baz => 23);
427
428 Default values for "stash" in Mojolicious::Controller, assigned for
429 every new request.
430
431 # Remove value
432 my $foo = delete $app->defaults->{foo};
433
434 # Assign multiple values at once
435 $app->defaults(foo => 'test', bar => 23);
436
437 dispatch
438 $app->dispatch(Mojolicious::Controller->new);
439
440 The heart of every Mojolicious application, calls the "static" and
441 "routes" dispatchers for every request and passes them a
442 Mojolicious::Controller object.
443
444 handler
445 $app->handler(Mojo::Transaction::HTTP->new);
446 $app->handler(Mojolicious::Controller->new);
447
448 Sets up the default controller and emits the "around_dispatch" hook for
449 every request.
450
451 helper
452 $app->helper(foo => sub {...});
453
454 Add or replace a helper that will be available as a method of the
455 controller object and the application object, as well as a function in
456 "ep" templates. For a full list of helpers that are available by
457 default see Mojolicious::Plugin::DefaultHelpers and
458 Mojolicious::Plugin::TagHelpers.
459
460 # Helper
461 $app->helper(cache => sub { state $cache = {} });
462
463 # Application
464 $app->cache->{foo} = 'bar';
465 my $result = $app->cache->{foo};
466
467 # Controller
468 $c->cache->{foo} = 'bar';
469 my $result = $c->cache->{foo};
470
471 # Template
472 % cache->{foo} = 'bar';
473 %= cache->{foo}
474
475 hook
476 $app->hook(after_dispatch => sub {...});
477
478 Extend Mojolicious with hooks, which allow code to be shared with all
479 requests indiscriminately, for a full list of available hooks see
480 "HOOKS".
481
482 # Dispatchers will not run if there's already a response code defined
483 $app->hook(before_dispatch => sub {
484 my $c = shift;
485 $c->render(text => 'Skipped static file server and router!')
486 if $c->req->url->path->to_route =~ /do_not_dispatch/;
487 });
488
489 new
490 my $app = Mojolicious->new;
491 my $app = Mojolicious->new(moniker => 'foo_bar');
492 my $app = Mojolicious->new({moniker => 'foo_bar'});
493
494 Construct a new Mojolicious application and call "startup". Will
495 automatically detect your home directory. Also sets up the renderer,
496 static file server, a default set of plugins and an "around_dispatch"
497 hook with the default exception handling.
498
499 plugin
500 $app->plugin('some_thing');
501 $app->plugin('some_thing', foo => 23);
502 $app->plugin('some_thing', {foo => 23});
503 $app->plugin('SomeThing');
504 $app->plugin('SomeThing', foo => 23);
505 $app->plugin('SomeThing', {foo => 23});
506 $app->plugin('MyApp::Plugin::SomeThing');
507 $app->plugin('MyApp::Plugin::SomeThing', foo => 23);
508 $app->plugin('MyApp::Plugin::SomeThing', {foo => 23});
509
510 Load a plugin, for a full list of example plugins included in the
511 Mojolicious distribution see "PLUGINS" in Mojolicious::Plugins.
512
513 server
514 $app->server(Mojo::Server->new);
515
516 Emits the "before_server_start" hook.
517
518 start
519 $app->start;
520 $app->start(@ARGV);
521
522 Start the command line interface for your application. For a full list
523 of commands that are available by default see "COMMANDS" in
524 Mojolicious::Commands. Note that the options "-h"/"--help", "--home"
525 and "-m"/"--mode", which are shared by all commands, will be parsed
526 from @ARGV during compile time.
527
528 # Always start daemon
529 $app->start('daemon', '-l', 'http://*:8080');
530
531 startup
532 $app->startup;
533
534 This is your main hook into the application, it will be called at
535 application startup. Meant to be overloaded in a subclass.
536
537 sub startup {
538 my $self = shift;
539 ...
540 }
541
543 In addition to the "ATTRIBUTES" and "METHODS" above you can also call
544 helpers on Mojolicious objects. This includes all helpers from
545 Mojolicious::Plugin::DefaultHelpers and
546 Mojolicious::Plugin::TagHelpers. Note that application helpers are
547 always called with a new default controller object, so they can't
548 depend on or change controller state, which includes request, response
549 and stash.
550
551 # Call helper
552 say $app->dumper({foo => 'bar'});
553
554 # Longer version
555 say $app->build_controller->helpers->dumper({foo => 'bar'});
556
558 The Mojolicious distribution includes a few files with different
559 licenses that have been bundled for internal use.
560
561 Mojolicious Artwork
562 Copyright (C) 2010-2018, Sebastian Riedel.
563
564 Licensed under the CC-SA License, Version 4.0
565 <http://creativecommons.org/licenses/by-sa/4.0>.
566
567 jQuery
568 Copyright (C) jQuery Foundation.
569
570 Licensed under the MIT License,
571 <http://creativecommons.org/licenses/MIT>.
572
573 prettify.js
574 Copyright (C) 2006, 2013 Google Inc..
575
576 Licensed under the Apache License, Version 2.0
577 <http://www.apache.org/licenses/LICENSE-2.0>.
578
580 Every major release of Mojolicious has a code name, these are the ones
581 that have been used in the past.
582
583 8.0, "Supervillain" (U+1F9B9)
584
585 7.0, "Doughnut" (U+1F369)
586
587 6.0, "Clinking Beer Mugs" (U+1F37B)
588
589 5.0, "Tiger Face" (U+1F42F)
590
591 4.0, "Top Hat" (U+1F3A9)
592
593 3.0, "Rainbow" (U+1F308)
594
595 2.0, "Leaf Fluttering In Wind" (U+1F343)
596
597 1.0, "Snowflake" (U+2744)
598
600 · Stix <https://stix.no> sponsored the creation of the Mojolicious logo
601 (designed by Nicolai Graesdal) and transferred its copyright to
602 Sebastian Riedel.
603
604 · Some of the work on this distribution has been sponsored by The Perl
605 Foundation <http://www.perlfoundation.org>.
606
608 Sebastian Riedel, "kraih@mojolicious.org"
609
611 Current members of the core team in alphabetical order:
612
613 Jan Henning Thorsen, "batman@mojolicious.org"
614
615 Joel Berger, "jberger@mojolicious.org"
616
617 Marcus Ramberg, "marcus@mojolicious.org"
618
619 The following members of the core team are currently on hiatus:
620
621 Abhijit Menon-Sen, "ams@cpan.org"
622
623 Glen Hinkle, "tempire@cpan.org"
624
626 In alphabetical order:
627
628 Adam Kennedy
629
630 Adriano Ferreira
631
632 Al Newkirk
633
634 Alex Efros
635
636 Alex Salimon
637
638 Alexander Karelas
639
640 Alexey Likhatskiy
641
642 Anatoly Sharifulin
643
644 Andre Parker
645
646 Andre Vieth
647
648 Andreas Guldstrand
649
650 Andreas Jaekel
651
652 Andreas Koenig
653
654 Andrew Fresh
655
656 Andrew Nugged
657
658 Andrey Khozov
659
660 Andrey Kuzmin
661
662 Andy Grundman
663
664 Aristotle Pagaltzis
665
666 Ashley Dev
667
668 Ask Bjoern Hansen
669
670 Audrey Tang
671
672 Ben Tyler
673
674 Ben van Staveren
675
676 Benjamin Erhart
677
678 Bernhard Graf
679
680 Breno G. de Oliveira
681
682 Brian Duggan
683
684 Brian Medley
685
686 Burak Gursoy
687
688 Ch Lamprecht
689
690 Charlie Brady
691
692 Chas. J. Owens IV
693
694 Chase Whitener
695
696 Christian Hansen
697
698 chromatic
699
700 Curt Tilmes
701
702 Dan Book
703
704 Daniel Kimsey
705
706 Daniel Mantovani
707
708 Danijel Tasov
709
710 Danny Thomas
711
712 David Davis
713
714 David Webb
715
716 Diego Kuperman
717
718 Dmitriy Shalashov
719
720 Dmitry Konstantinov
721
722 Dominik Jarmulowicz
723
724 Dominique Dumont
725
726 Dotan Dimet
727
728 Douglas Christopher Wilson
729
730 Ettore Di Giacinto
731
732 Eugen Konkov
733
734 Eugene Toropov
735
736 Flavio Poletti
737
738 Gisle Aas
739
740 Graham Barr
741
742 Graham Knop
743
744 Henry Tang
745
746 Hideki Yamamura
747
748 Hiroki Toyokawa
749
750 Ian Goodacre
751
752 Ilya Chesnokov
753
754 Ilya Rassadin
755
756 James Duncan
757
758 Jan Jona Javorsek
759
760 Jan Schmidt
761
762 Jaroslav Muhin
763
764 Jesse Vincent
765
766 Johannes Plunien
767
768 John Kingsley
769
770 Jonathan Yu
771
772 Josh Leder
773
774 Kazuhiro Shibuya
775
776 Kevin Old
777
778 Kitamura Akatsuki
779
780 Klaus S. Madsen
781
782 Knut Arne Bjorndal
783
784 Lars Balker Rasmussen
785
786 Lee Johnson
787
788 Leon Brocard
789
790 Magnus Holm
791
792 Maik Fischer
793
794 Mark Fowler
795
796 Mark Grimes
797
798 Mark Stosberg
799
800 Marty Tennison
801
802 Matt S Trout
803
804 Matthew Lineen
805
806 Maksym Komar
807
808 Maxim Vuets
809
810 Michael Gregorowicz
811
812 Michael Harris
813
814 Mike Magowan
815
816 Mirko Westermeier
817
818 Mons Anderson
819
820 Moritz Lenz
821
822 Neil Watkiss
823
824 Nic Sandfield
825
826 Nils Diewald
827
828 Oleg Zhelo
829
830 Olivier Mengue
831
832 Pascal Gaudette
833
834 Paul Evans
835
836 Paul Robins
837
838 Paul Tomlin
839
840 Pavel Shaydo
841
842 Pedro Melo
843
844 Peter Edwards
845
846 Pierre-Yves Ritschard
847
848 Piotr Roszatycki
849
850 Quentin Carbonneaux
851
852 Rafal Pocztarski
853
854 Randal Schwartz
855
856 Richard Elberger
857
858 Rick Delaney
859
860 Robert Hicks
861
862 Robin Lee
863
864 Roland Lammel
865
866 Roy Storey
867
868 Ryan Jendoubi
869
870 Salvador Fandino
871
872 Santiago Zarate
873
874 Sascha Kiefer
875
876 Scott Wiersdorf
877
878 Sergey Zasenko
879
880 Simon Bertrang
881
882 Simone Tampieri
883
884 Shu Cho
885
886 Skye Shaw
887
888 Stanis Trendelenburg
889
890 Steffen Ullrich
891
892 Stephan Kulow
893
894 Stephane Este-Gracias
895
896 Stevan Little
897
898 Steve Atkins
899
900 Tatsuhiko Miyagawa
901
902 Terrence Brannon
903
904 Tianon Gravi
905
906 Tomas Znamenacek
907
908 Tudor Constantin
909
910 Ulrich Habel
911
912 Ulrich Kautz
913
914 Uwe Voelker
915
916 Viacheslav Tykhanovskyi
917
918 Victor Engmark
919
920 Viliam Pucik
921
922 Wes Cravens
923
924 William Lindley
925
926 Yaroslav Korshak
927
928 Yuki Kimoto
929
930 Zak B. Elep
931
932 Zoffix Znet
933
935 Copyright (C) 2008-2018, Sebastian Riedel and others.
936
937 This program is free software, you can redistribute it and/or modify it
938 under the terms of the Artistic License version 2.0.
939
941 <https://github.com/mojolicious/mojo>, Mojolicious::Guides,
942 <https://mojolicious.org>.
943
944
945
946perl v5.28.0 2018-11-08 Mojolicious(3)