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

Revision 10417, 2.0 kB (checked in by daisuke, 5 years ago)

Exporter使わない版

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