-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathCatalyst.pm
5097 lines (3688 loc) · 155 KB
/
Catalyst.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Catalyst;
use Moose;
use Moose::Meta::Class ();
extends 'Catalyst::Component';
use Moose::Util qw/find_meta/;
use namespace::clean -except => 'meta';
use Catalyst::Exception;
use Catalyst::Exception::Detach;
use Catalyst::Exception::Go;
use Catalyst::Log;
use Catalyst::Request;
use Catalyst::Request::Upload;
use Catalyst::Response;
use Catalyst::Utils;
use Catalyst::Controller;
use Data::OptList;
use Devel::InnerPackage ();
use Module::Pluggable::Object ();
use Text::SimpleTable ();
use Path::Class::Dir ();
use Path::Class::File ();
use URI ();
use URI::http;
use URI::https;
use HTML::Entities;
use Tree::Simple qw/use_weak_refs/;
use Tree::Simple::Visitor::FindByUID;
use Class::C3::Adopt::NEXT;
use List::Util qw/uniq/;
use attributes;
use String::RewritePrefix;
use Catalyst::EngineLoader;
use utf8;
use Carp qw/croak carp shortmess/;
use Try::Tiny;
use Safe::Isa;
use Moose::Util 'find_meta';
use Plack::Middleware::Conditional;
use Plack::Middleware::ReverseProxy;
use Plack::Middleware::IIS6ScriptNameFix;
use Plack::Middleware::IIS7KeepAliveFix;
use Plack::Middleware::LighttpdScriptNameFix;
use Plack::Middleware::ContentLength;
use Plack::Middleware::Head;
use Plack::Middleware::HTTPExceptions;
use Plack::Middleware::FixMissingBodyInRedirect;
use Plack::Middleware::MethodOverride;
use Plack::Middleware::RemoveRedundantBody;
use Catalyst::Middleware::Stash;
use Plack::Util;
use Class::Load 'load_class';
use Encode 2.21 'decode_utf8', 'encode_utf8';
use Scalar::Util;
our $VERSION = '5.90130';
$VERSION =~ tr/_//d;
BEGIN { require 5.008003; }
has stack => (is => 'ro', default => sub { [] });
has state => (is => 'rw', default => 0);
has stats => (is => 'rw');
has action => (is => 'rw');
has counter => (is => 'rw', default => sub { {} });
has request => (
is => 'rw',
default => sub {
my $self = shift;
my $class = ref $self;
my $composed_request_class = $class->composed_request_class;
return $composed_request_class->new( $self->_build_request_constructor_args);
},
predicate => 'has_request',
lazy => 1,
);
sub _build_request_constructor_args {
my $self = shift;
my %p = ( _log => $self->log );
$p{_uploadtmp} = $self->_uploadtmp if $self->_has_uploadtmp;
$p{data_handlers} = {$self->registered_data_handlers};
$p{_use_hash_multivalue} = $self->config->{use_hash_multivalue_in_request}
if $self->config->{use_hash_multivalue_in_request};
\%p;
}
sub composed_request_class {
my $class = shift;
return $class->_composed_request_class if $class->_composed_request_class;
my @traits = (@{$class->request_class_traits||[]}, @{$class->config->{request_class_traits}||[]});
# For each trait listed, figure out what the namespace is. First we try the $trait
# as it is in the config. Then try $MyApp::TraitFor::Request:$trait. Last we try
# Catalyst::TraitFor::Request::$trait. If none load, throw error.
my $trait_ns = 'TraitFor::Request';
my @normalized_traits = map {
Class::Load::load_first_existing_class($_, $class.'::'.$trait_ns.'::'. $_, 'Catalyst::'.$trait_ns.'::'.$_)
} @traits;
if ($class->debug && scalar(@normalized_traits)) {
my $column_width = Catalyst::Utils::term_width() - 6;
my $t = Text::SimpleTable->new($column_width);
$t->row($_) for @normalized_traits;
$class->log->debug( "Composed Request Class Traits:\n" . $t->draw . "\n" );
}
return $class->_composed_request_class(Moose::Util::with_traits($class->request_class, @normalized_traits));
}
has response => (
is => 'rw',
default => sub {
my $self = shift;
my $class = ref $self;
my $composed_response_class = $class->composed_response_class;
return $composed_response_class->new( $self->_build_response_constructor_args);
},
predicate=>'has_response',
lazy => 1,
);
sub _build_response_constructor_args {
return +{
_log => $_[0]->log,
encoding => $_[0]->encoding,
};
}
sub composed_response_class {
my $class = shift;
return $class->_composed_response_class if $class->_composed_response_class;
my @traits = (@{$class->response_class_traits||[]}, @{$class->config->{response_class_traits}||[]});
my $trait_ns = 'TraitFor::Response';
my @normalized_traits = map {
Class::Load::load_first_existing_class($_, $class.'::'.$trait_ns.'::'. $_, 'Catalyst::'.$trait_ns.'::'.$_)
} @traits;
if ($class->debug && scalar(@normalized_traits)) {
my $column_width = Catalyst::Utils::term_width() - 6;
my $t = Text::SimpleTable->new($column_width);
$t->row($_) for @normalized_traits;
$class->log->debug( "Composed Response Class Traits:\n" . $t->draw . "\n" );
}
return $class->_composed_response_class(Moose::Util::with_traits($class->response_class, @normalized_traits));
}
has namespace => (is => 'rw');
sub depth { scalar @{ shift->stack || [] }; }
sub comp { shift->component(@_) }
sub req {
my $self = shift; return $self->request(@_);
}
sub res {
my $self = shift; return $self->response(@_);
}
# For backwards compatibility
sub finalize_output { shift->finalize_body(@_) };
# For statistics
our $COUNT = 1;
our $START = time;
our $RECURSION = 1000;
our $DETACH = Catalyst::Exception::Detach->new;
our $GO = Catalyst::Exception::Go->new;
#I imagine that very few of these really
#need to be class variables. if any.
#maybe we should just make them attributes with a default?
__PACKAGE__->mk_classdata($_)
for qw/components arguments dispatcher engine log dispatcher_class
engine_loader context_class request_class response_class stats_class
setup_finished _psgi_app loading_psgi_file run_options _psgi_middleware
_data_handlers _encoding _encode_check finalized_default_middleware
request_class_traits response_class_traits stats_class_traits
_composed_request_class _composed_response_class _composed_stats_class/;
__PACKAGE__->dispatcher_class('Catalyst::Dispatcher');
__PACKAGE__->request_class('Catalyst::Request');
__PACKAGE__->response_class('Catalyst::Response');
__PACKAGE__->stats_class('Catalyst::Stats');
sub composed_stats_class {
my $class = shift;
return $class->_composed_stats_class if $class->_composed_stats_class;
my @traits = (@{$class->stats_class_traits||[]}, @{$class->config->{stats_class_traits}||[]});
my $trait_ns = 'TraitFor::Stats';
my @normalized_traits = map {
Class::Load::load_first_existing_class($_, $class.'::'.$trait_ns.'::'. $_, 'Catalyst::'.$trait_ns.'::'.$_)
} @traits;
if ($class->debug && scalar(@normalized_traits)) {
my $column_width = Catalyst::Utils::term_width() - 6;
my $t = Text::SimpleTable->new($column_width);
$t->row($_) for @normalized_traits;
$class->log->debug( "Composed Stats Class Traits:\n" . $t->draw . "\n" );
}
return $class->_composed_stats_class(Moose::Util::with_traits($class->stats_class, @normalized_traits));
}
__PACKAGE__->_encode_check(Encode::FB_CROAK | Encode::LEAVE_SRC);
sub import {
my ( $class, @arguments ) = @_;
# We have to limit $class to Catalyst to avoid pushing Catalyst upon every
# callers @ISA.
return unless $class eq 'Catalyst';
my $caller = caller();
return if $caller eq 'main';
my $meta = Moose::Meta::Class->initialize($caller);
unless ( $caller->isa('Catalyst') ) {
my @superclasses = ($meta->superclasses, $class, 'Catalyst::Controller');
$meta->superclasses(@superclasses);
}
# Avoid possible C3 issues if 'Moose::Object' is already on RHS of MyApp
$meta->superclasses(grep { $_ ne 'Moose::Object' } $meta->superclasses);
unless( $meta->has_method('meta') ){
if ($Moose::VERSION >= 1.15) {
$meta->_add_meta_method('meta');
}
else {
$meta->add_method(meta => sub { Moose::Meta::Class->initialize("${caller}") } );
}
}
$caller->arguments( [@arguments] );
$caller->setup_home;
}
sub _application { $_[0] }
=encoding UTF-8
=head1 NAME
Catalyst - The Elegant MVC Web Application Framework
=head1 SYNOPSIS
See the L<Catalyst::Manual> distribution for comprehensive
documentation and tutorials.
# Install Catalyst::Devel for helpers and other development tools
# use the helper to create a new application
catalyst.pl MyApp
# add models, views, controllers
script/myapp_create.pl model MyDatabase DBIC::Schema create=static dbi:SQLite:/path/to/db
script/myapp_create.pl view MyTemplate TT
script/myapp_create.pl controller Search
# built in testserver -- use -r to restart automatically on changes
# --help to see all available options
script/myapp_server.pl
# command line testing interface
script/myapp_test.pl /yada
### in lib/MyApp.pm
use Catalyst qw/-Debug/; # include plugins here as well
### In lib/MyApp/Controller/Root.pm (autocreated)
sub foo : Chained('/') Args() { # called for /foo, /foo/1, /foo/1/2, etc.
my ( $self, $c, @args ) = @_; # args are qw/1 2/ for /foo/1/2
$c->stash->{template} = 'foo.tt'; # set the template
# lookup something from db -- stash vars are passed to TT
$c->stash->{data} =
$c->model('Database::Foo')->search( { country => $args[0] } );
if ( $c->req->params->{bar} ) { # access GET or POST parameters
$c->forward( 'bar' ); # process another action
# do something else after forward returns
}
}
# The foo.tt TT template can use the stash data from the database
[% WHILE (item = data.next) %]
[% item.foo %]
[% END %]
# called for /bar/of/soap, /bar/of/soap/10, etc.
sub bar : Chained('/') PathPart('/bar/of/soap') Args() { ... }
# called after all actions are finished
sub end : Action {
my ( $self, $c ) = @_;
if ( scalar @{ $c->error } ) { ... } # handle errors
return if $c->res->body; # already have a response
$c->forward( 'MyApp::View::TT' ); # render template
}
See L<Catalyst::Manual::Intro> for additional information.
=head1 DESCRIPTION
Catalyst is a modern framework for making web applications without the
pain usually associated with this process. This document is a reference
to the main Catalyst application. If you are a new user, we suggest you
start with L<Catalyst::Manual::Tutorial> or L<Catalyst::Manual::Intro>.
See L<Catalyst::Manual> for more documentation.
Catalyst plugins can be loaded by naming them as arguments to the "use
Catalyst" statement. Omit the C<Catalyst::Plugin::> prefix from the
plugin name, i.e., C<Catalyst::Plugin::My::Module> becomes
C<My::Module>.
use Catalyst qw/My::Module/;
If your plugin starts with a name other than C<Catalyst::Plugin::>, you can
fully qualify the name by using a unary plus:
use Catalyst qw/
My::Module
+Fully::Qualified::Plugin::Name
/;
Special flags like C<-Debug> can also be specified as
arguments when Catalyst is loaded:
use Catalyst qw/-Debug My::Module/;
The position of plugins and flags in the chain is important, because
they are loaded in the order in which they appear.
The following flags are supported:
=head2 -Debug
Enables debug output. You can also force this setting from the system
environment with CATALYST_DEBUG or <MYAPP>_DEBUG. The environment
settings override the application, with <MYAPP>_DEBUG having the highest
priority.
This sets the log level to 'debug' and enables full debug output on the
error screen. If you only want the latter, see L<< $c->debug >>.
=head2 -Home
Forces Catalyst to use a specific home directory, e.g.:
use Catalyst qw[-Home=/usr/mst];
This can also be done in the shell environment by setting either the
C<CATALYST_HOME> environment variable or C<MYAPP_HOME>; where C<MYAPP>
is replaced with the uppercased name of your application, any "::" in
the name will be replaced with underscores, e.g. MyApp::Web should use
MYAPP_WEB_HOME. If both variables are set, the MYAPP_HOME one will be used.
If none of these are set, Catalyst will attempt to automatically detect the
home directory. If you are working in a development environment, Catalyst
will try and find the directory containing either Makefile.PL, Build.PL,
dist.ini, or cpanfile. If the application has been installed into the system
(i.e. you have done C<make install>), then Catalyst will use the path to your
application module, without the .pm extension (e.g., /foo/MyApp if your
application was installed at /foo/MyApp.pm)
=head2 -Log
use Catalyst '-Log=warn,fatal,error';
Specifies a comma-delimited list of log levels.
=head2 -Stats
Enables statistics collection and reporting.
use Catalyst qw/-Stats=1/;
You can also force this setting from the system environment with CATALYST_STATS
or <MYAPP>_STATS. The environment settings override the application, with
<MYAPP>_STATS having the highest priority.
Stats are also enabled if L<< debugging |/"-Debug" >> is enabled.
=head1 METHODS
=head2 INFORMATION ABOUT THE CURRENT REQUEST
=head2 $c->action
Returns a L<Catalyst::Action> object for the current action, which
stringifies to the action name. See L<Catalyst::Action>.
=head2 $c->namespace
Returns the namespace of the current action, i.e., the URI prefix
corresponding to the controller of the current action. For example:
# in Controller::Foo::Bar
$c->namespace; # returns 'foo/bar';
=head2 $c->request
=head2 $c->req
Returns the current L<Catalyst::Request> object, giving access to
information about the current client request (including parameters,
cookies, HTTP headers, etc.). See L<Catalyst::Request>.
There is a predicate method C<has_request> that returns true if the
request object has been created. This is something you might need to
check if you are writing plugins that run before a request is finalized.
=head2 REQUEST FLOW HANDLING
=head2 $c->forward( $action [, \@arguments ] )
=head2 $c->forward( $class, $method, [, \@arguments ] )
=head2 $c->forward( $component_instance, $method, [, \@arguments ] )
This is one way of calling another action (method) in the same or
a different controller. You can also use C<< $self->my_method($c, @args) >>
in the same controller or C<< $c->controller('MyController')->my_method($c, @args) >>
in a different controller.
The main difference is that 'forward' uses some of the Catalyst request
cycle overhead, including debugging, which may be useful to you. On the
other hand, there are some complications to using 'forward', restrictions
on values returned from 'forward', and it may not handle errors as you prefer.
Whether you use 'forward' or not is up to you; it is not considered superior to
the other ways to call a method.
'forward' calls another action, by its private name. If you give a
class name but no method, C<process()> is called. You may also optionally
pass arguments in an arrayref. The action will receive the arguments in
C<@_> and C<< $c->req->args >>. Upon returning from the function,
C<< $c->req->args >> will be restored to the previous values.
Any data C<return>ed from the action forwarded to, will be returned by the
call to forward.
my $foodata = $c->forward('/foo');
$c->forward('index');
$c->forward(qw/Model::DBIC::Foo do_stuff/);
$c->forward('View::TT');
Note that L<< forward|/"$c->forward( $action [, \@arguments ] )" >> implies
an C<< eval { } >> around the call (actually
L<< execute|/"$c->execute( $class, $coderef )" >> does), thus rendering all
exceptions thrown by the called action non-fatal and pushing them onto
$c->error instead. If you want C<die> to propagate you need to do something
like:
$c->forward('foo');
die join "\n", @{ $c->error } if @{ $c->error };
Or make sure to always return true values from your actions and write
your code like this:
$c->forward('foo') || return;
Another note is that C<< $c->forward >> always returns a scalar because it
actually returns $c->state which operates in a scalar context.
Thus, something like:
return @array;
in an action that is forwarded to is going to return a scalar,
i.e. how many items are in that array, which is probably not what you want.
If you need to return an array then return a reference to it,
or stash it like so:
$c->stash->{array} = \@array;
and access it from the stash.
Keep in mind that the C<end> method used is that of the caller action. So a C<< $c->detach >> inside a forwarded action would run the C<end> method from the original action requested.
If you call c<forward> with the name of a component class or instance, rather than an action name
or instance, we invoke the C<process> action on that class or instance, or whatever action you
specific via the second argument $method.
=cut
sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
=head2 $c->detach( $action [, \@arguments ] )
=head2 $c->detach( $class, $method, [, \@arguments ] )
=head2 $c->detach()
The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but
doesn't return to the previous action when processing is finished.
When called with no arguments it escapes the processing chain entirely.
=cut
sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
=head2 $c->visit( $action [, \@arguments ] )
=head2 $c->visit( $action [, \@captures, \@arguments ] )
=head2 $c->visit( $class, $method, [, \@arguments ] )
=head2 $c->visit( $class, $method, [, \@captures, \@arguments ] )
Almost the same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>,
but does a full dispatch, instead of just calling the new C<$action> /
C<< $class->$method >>. This means that C<begin>, C<auto> and the method
you go to are called, just like a new request.
In addition both C<< $c->action >> and C<< $c->namespace >> are localized.
This means, for example, that C<< $c->action >> methods such as
L<name|Catalyst::Action/name>, L<class|Catalyst::Action/class> and
L<reverse|Catalyst::Action/reverse> return information for the visited action
when they are invoked within the visited action. This is different from the
behavior of L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, which
continues to use the $c->action object from the caller action even when
invoked from the called action.
C<< $c->stash >> is kept unchanged.
In effect, L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >>
allows you to "wrap" another action, just as it would have been called by
dispatching from a URL, while the analogous
L<< go|/"$c->go( $action [, \@captures, \@arguments ] )" >> allows you to
transfer control to another action as if it had been reached directly from a URL.
=cut
sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
=head2 $c->go( $action [, \@arguments ] )
=head2 $c->go( $action [, \@captures, \@arguments ] )
=head2 $c->go( $class, $method, [, \@arguments ] )
=head2 $c->go( $class, $method, [, \@captures, \@arguments ] )
The relationship between C<go> and
L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> is the same as
the relationship between
L<< forward|/"$c->forward( $class, $method, [, \@arguments ] )" >> and
L<< detach|/"$c->detach( $action [, \@arguments ] )" >>. Like C<< $c->visit >>,
C<< $c->go >> will perform a full dispatch on the specified action or method,
with localized C<< $c->action >> and C<< $c->namespace >>. Like C<detach>,
C<go> escapes the processing of the current request chain on completion, and
does not return to its caller.
@arguments are arguments to the final destination of $action. @captures are
arguments to the intermediate steps, if any, on the way to the final sub of
$action.
=cut
sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
=head2 $c->response
=head2 $c->res
Returns the current L<Catalyst::Response> object, see there for details.
There is a predicate method C<has_response> that returns true if the
request object has been created. This is something you might need to
check if you are writing plugins that run before a request is finalized.
=head2 $c->stash
Returns a hashref to the stash, which may be used to store data and pass
it between components during a request. You can also set hash keys by
passing arguments. The stash is automatically sent to the view. The
stash is cleared at the end of a request; it cannot be used for
persistent storage (for this you must use a session; see
L<Catalyst::Plugin::Session> for a complete system integrated with
Catalyst).
$c->stash->{foo} = $bar;
$c->stash( { moose => 'majestic', qux => 0 } );
$c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
# stash is automatically passed to the view for use in a template
$c->forward( 'MyApp::View::TT' );
The stash hash is currently stored in the PSGI C<$env> and is managed by
L<Catalyst::Middleware::Stash>. Since it's part of the C<$env> items in
the stash can be accessed in sub applications mounted under your main
L<Catalyst> application. For example if you delegate the response of an
action to another L<Catalyst> application, that sub application will have
access to all the stash keys of the main one, and if can of course add
more keys of its own. However those new keys will not 'bubble' back up
to the main application.
For more information the best thing to do is to review the test case:
t/middleware-stash.t in the distribution /t directory.
=cut
sub stash {
my $c = shift;
$c->log->error("You are requesting the stash but you don't have a context") unless blessed $c;
return Catalyst::Middleware::Stash::get_stash($c->req->env)->(@_);
}
=head2 $c->error
=head2 $c->error($error, ...)
=head2 $c->error($arrayref)
Returns an arrayref containing error messages. If Catalyst encounters an
error while processing a request, it stores the error in $c->error. This
method should only be used to store fatal error messages.
my @error = @{ $c->error };
Add a new error.
$c->error('Something bad happened');
Calling this will always return an arrayref (if there are no errors it
will be an empty arrayref.
=cut
sub error {
my $c = shift;
if ( $_[0] ) {
my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
croak @$error unless ref $c;
push @{ $c->{error} }, @$error;
}
elsif ( defined $_[0] ) { $c->{error} = undef }
return $c->{error} || [];
}
=head2 $c->state
Contains the return value of the last executed action.
Note that << $c->state >> operates in a scalar context which means that all
values it returns are scalar.
Please note that if an action throws an exception, the value of state
should no longer be considered the return if the last action. It is generally
going to be 0, which indicates an error state. Examine $c->error for error
details.
=head2 $c->clear_errors
Clear errors. You probably don't want to clear the errors unless you are
implementing a custom error screen.
This is equivalent to running
$c->error(0);
=cut
sub clear_errors {
my $c = shift;
$c->error(0);
}
=head2 $c->has_errors
Returns true if you have errors
=cut
sub has_errors { scalar(@{shift->error}) ? 1:0 }
=head2 $c->last_error
Returns the most recent error in the stack (the one most recently added...)
or nothing if there are no errors. This does not modify the contents of the
error stack.
=cut
sub last_error {
my (@errs) = @{shift->error};
return scalar(@errs) ? $errs[-1]: undef;
}
=head2 shift_errors
shifts the most recently added error off the error stack and returns it. Returns
nothing if there are no more errors.
=cut
sub shift_errors {
my ($self) = @_;
my @errors = @{$self->error};
my $err = shift(@errors);
$self->{error} = \@errors;
return $err;
}
=head2 pop_errors
pops the most recently added error off the error stack and returns it. Returns
nothing if there are no more errors.
=cut
sub pop_errors {
my ($self) = @_;
my @errors = @{$self->error};
my $err = pop(@errors);
$self->{error} = \@errors;
return $err;
}
sub _comp_search_prefixes {
my $c = shift;
return map $c->components->{ $_ }, $c->_comp_names_search_prefixes(@_);
}
# search components given a name and some prefixes
sub _comp_names_search_prefixes {
my ( $c, $name, @prefixes ) = @_;
my $appclass = ref $c || $c;
my $filter = "^${appclass}::(" . join( '|', @prefixes ) . ')::';
$filter = qr/$filter/; # Compile regex now rather than once per loop
# map the original component name to the sub part that we will search against
my %eligible = map { my $n = $_; $n =~ s{^$appclass\::[^:]+::}{}; $_ => $n; }
grep { /$filter/ } keys %{ $c->components };
# undef for a name will return all
return keys %eligible if !defined $name;
my $query = $name->$_isa('Regexp') ? $name : qr/^$name$/i;
my @result = grep { $eligible{$_} =~ m{$query} } keys %eligible;
return @result if @result;
# if we were given a regexp to search against, we're done.
return if $name->$_isa('Regexp');
# skip regexp fallback if configured
return
if $appclass->config->{disable_component_resolution_regex_fallback};
# regexp fallback
$query = qr/$name/i;
@result = grep { $eligible{ $_ } =~ m{$query} } keys %eligible;
# no results? try against full names
if( !@result ) {
@result = grep { m{$query} } keys %eligible;
}
# don't warn if we didn't find any results, it just might not exist
if( @result ) {
# Disgusting hack to work out correct method name
my $warn_for = lc $prefixes[0];
my $msg = "Used regexp fallback for \$c->${warn_for}('${name}'), which found '" .
(join '", "', @result) . "'. Relying on regexp fallback behavior for " .
"component resolution is unreliable and unsafe.";
my $short = $result[0];
# remove the component namespace prefix
$short =~ s/.*?(Model|Controller|View):://;
my $shortmess = Carp::shortmess('');
if ($shortmess =~ m#Catalyst/Plugin#) {
$msg .= " You probably need to set '$short' instead of '${name}' in this " .
"plugin's config";
} elsif ($shortmess =~ m#Catalyst/lib/(View|Controller)#) {
$msg .= " You probably need to set '$short' instead of '${name}' in this " .
"component's config";
} else {
$msg .= " You probably meant \$c->${warn_for}('$short') instead of \$c->${warn_for}('${name}'), " .
"but if you really wanted to search, pass in a regexp as the argument " .
"like so: \$c->${warn_for}(qr/${name}/)";
}
$c->log->warn( "${msg}$shortmess" );
}
return @result;
}
# Find possible names for a prefix
sub _comp_names {
my ( $c, @prefixes ) = @_;
my $appclass = ref $c || $c;
my $filter = "^${appclass}::(" . join( '|', @prefixes ) . ')::';
my @names = map { s{$filter}{}; $_; }
$c->_comp_names_search_prefixes( undef, @prefixes );
return @names;
}
# Filter a component before returning by calling ACCEPT_CONTEXT if available
sub _filter_component {
my ( $c, $comp, @args ) = @_;
if(ref $comp eq 'CODE') {
$comp = $comp->();
}
if ( eval { $comp->can('ACCEPT_CONTEXT'); } ) {
return $comp->ACCEPT_CONTEXT( $c, @args );
}
$c->log->warn("You called component '${\$comp->catalyst_component_name}' with arguments [@args], but this component does not ACCEPT_CONTEXT, so args are ignored.") if scalar(@args) && $c->debug;
return $comp;
}
=head2 COMPONENT ACCESSORS
=head2 $c->controller($name)
Gets a L<Catalyst::Controller> instance by name.
$c->controller('Foo')->do_stuff;
If the name is omitted, will return the controller for the dispatched
action.
If you want to search for controllers, pass in a regexp as the argument.
# find all controllers that start with Foo
my @foo_controllers = $c->controller(qr{^Foo});
=cut
sub controller {
my ( $c, $name, @args ) = @_;
my $appclass = ref($c) || $c;
if( $name ) {
unless ( $name->$_isa('Regexp') ) { # Direct component hash lookup to avoid costly regexps
my $comps = $c->components;
my $check = $appclass."::Controller::".$name;
return $c->_filter_component( $comps->{$check}, @args ) if exists $comps->{$check};
foreach my $path (@{$appclass->config->{ setup_components }->{ search_extra }}) {
next unless $path =~ /.*::Controller/;
$check = $path."::".$name;
return $c->_filter_component( $comps->{$check}, @args ) if exists $comps->{$check};
}
}
my @result = $c->_comp_search_prefixes( $name, qw/Controller C/ );
return map { $c->_filter_component( $_, @args ) } @result if ref $name;
return $c->_filter_component( $result[ 0 ], @args );
}
return $c->component( $c->action->class );
}
=head2 $c->model($name)
Gets a L<Catalyst::Model> instance by name.
$c->model('Foo')->do_stuff;
Any extra arguments are directly passed to ACCEPT_CONTEXT, if the model
defines ACCEPT_CONTEXT. If it does not, the args are discarded.
If the name is omitted, it will look for
- a model object in $c->stash->{current_model_instance}, then
- a model name in $c->stash->{current_model}, then
- a config setting 'default_model', or
- check if there is only one model, and return it if that's the case.
If you want to search for models, pass in a regexp as the argument.
# find all models that start with Foo
my @foo_models = $c->model(qr{^Foo});
=cut
sub model {
my ( $c, $name, @args ) = @_;
my $appclass = ref($c) || $c;
if( $name ) {
unless ( $name->$_isa('Regexp') ) { # Direct component hash lookup to avoid costly regexps
my $comps = $c->components;
my $check = $appclass."::Model::".$name;
return $c->_filter_component( $comps->{$check}, @args ) if exists $comps->{$check};
foreach my $path (@{$appclass->config->{ setup_components }->{ search_extra }}) {
next unless $path =~ /.*::Model/;
$check = $path."::".$name;
return $c->_filter_component( $comps->{$check}, @args ) if exists $comps->{$check};
}
}
my @result = $c->_comp_search_prefixes( $name, qw/Model M/ );
return map { $c->_filter_component( $_, @args ) } @result if ref $name;
return $c->_filter_component( $result[ 0 ], @args );
}
if (ref $c) {
return $c->stash->{current_model_instance}
if $c->stash->{current_model_instance};
return $c->model( $c->stash->{current_model} )
if $c->stash->{current_model};
}
return $c->model( $appclass->config->{default_model} )
if $appclass->config->{default_model};
my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/);
if( $rest ) {
$c->log->warn( Carp::shortmess('Calling $c->model() will return a random model unless you specify one of:') );
$c->log->warn( '* $c->config(default_model => "the name of the default model to use")' );
$c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' );
$c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' );
$c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
}
return $c->_filter_component( $comp );
}
=head2 $c->view($name)
Gets a L<Catalyst::View> instance by name.
$c->view('Foo')->do_stuff;
Any extra arguments are directly passed to ACCEPT_CONTEXT.
If the name is omitted, it will look for
- a view object in $c->stash->{current_view_instance}, then
- a view name in $c->stash->{current_view}, then
- a config setting 'default_view', or
- check if there is only one view, and return it if that's the case.
If you want to search for views, pass in a regexp as the argument.
# find all views that start with Foo
my @foo_views = $c->view(qr{^Foo});
=cut
sub view {
my ( $c, $name, @args ) = @_;
my $appclass = ref($c) || $c;
if( $name ) {
unless ( $name->$_isa('Regexp') ) { # Direct component hash lookup to avoid costly regexps
my $comps = $c->components;
my $check = $appclass."::View::".$name;
if( exists $comps->{$check} ) {
return $c->_filter_component( $comps->{$check}, @args );
}
else {
$c->log->warn( "Attempted to use view '$check', but does not exist" );
}
foreach my $path (@{$appclass->config->{ setup_components }->{ search_extra }}) {
next unless $path =~ /.*::View/;
$check = $path."::".$name;
return $c->_filter_component( $comps->{$check}, @args ) if exists $comps->{$check};
}
}
my @result = $c->_comp_search_prefixes( $name, qw/View V/ );
return map { $c->_filter_component( $_, @args ) } @result if ref $name;
return $c->_filter_component( $result[ 0 ], @args );
}
if (ref $c) {
return $c->stash->{current_view_instance}
if $c->stash->{current_view_instance};
return $c->view( $c->stash->{current_view} )
if $c->stash->{current_view};
}
return $c->view( $appclass->config->{default_view} )
if $appclass->config->{default_view};
my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/);
if( $rest ) {
$c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' );
$c->log->warn( '* $c->config(default_view => "the name of the default view to use")' );
$c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' );
$c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' );
$c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
}
return $c->_filter_component( $comp );
}
=head2 $c->controllers
Returns the available names which can be passed to $c->controller
=cut