root/lang/perl/HTTPx-Dispatcher/trunk/lib/HTTPx/Dispatcher.pm @ 10418

Revision 10418, 1.8 kB (checked in by tokuhirom, 5 years ago)

黒魔術レス

Line 
1package HTTPx::Dispatcher;
2use strict;
3use warnings;
4use 5.00800;
5our $VERSION = '0.01';
6use Class::Data::Inheritable;
7use HTTPx::Dispatcher::Rule;
8use Scalar::Util qw/blessed/;
9use Carp;
10use base qw/Exporter/;
11
12our @EXPORT = qw/connect match uri_for/;
13
14my $rules;
15
16sub connect
17{
18    my $pkg = caller(0);
19    my @args = @_;
20
21    push @{ $rules->{$pkg} } , HTTPx::Dispatcher::Rule->new(@args);
22}
23
24sub match
25{
26    my ($class, $req) = @_;
27    croak "request required" unless blessed $req;
28
29    for my $rule (@{ $rules->{$class} }) {
30        if (my $result = $rule->match($req)) {
31            return $result;
32        }
33    }
34    return; # no match.
35}
36
37sub uri_for
38{
39    my ($class, @args) = @_;
40
41    for my $rule ( @{ $rules->{$class} } ) {
42        if (my $result = $rule->uri_for( @args ) ) {
43            return $result;
44        }
45    }
46}
47
481;
49__END__
50
51=for stopwords TODO URI uri
52
53=encoding utf8
54
55=head1 NAME
56
57HTTPx::Dispatcher - the uri dispatcher
58
59=head1 SYNOPSIS
60
61    package Your::Dispatcher;
62    use HTTPx::Dispatcher;
63
64    connect ':controller/:action/:id';
65
66    package Your::Handler;
67    use HTTP::Engine;
68    use Your::Dispatcher;
69    use UNIVERSAL::require;
70
71    HTTP::Engine->new(
72        'config.yaml',
73        handle_request => sub {
74            my $c = shift;
75            my $rule = Your::Dispatcher->match($c->req->uri);
76            $rule->{controller}->use or die 'hoge';
77            my $action = $rule->{action};
78            $rule->{controller}->$action( $c->req );
79        }
80    );
81
82=head1 DESCRIPTION
83
84HTTPx::Dispatcher is URI Dispatcher.
85
86=head1 AUTHOR
87
88Tokuhiro Matsuno E<lt>tokuhirom@gmail.comE<gt>
89
90=head1 SEE ALSO
91
92L<HTTP::Engine>, L<Routes>
93
94=head1 LICENSE
95
96This library is free software; you can redistribute it and/or modify
97it under the same terms as Perl itself.
98
99=cut
Note: See TracBrowser for help on using the browser.