File Coverage

blib/lib/CGI/Application/Plugin/Config/Context.pm
Criterion Covered Total %
statement 103 111 92.7
branch 38 48 79.1
condition 5 11 45.4
subroutine 20 20 100.0
pod 6 7 85.7
total 172 197 87.3


line stmt bran cond sub pod time code
1             package CGI::Application::Plugin::Config::Context;
2              
3 13     13   470807 use warnings;
  13         35  
  13         530  
4 13     13   78 use strict;
  13         22  
  13         549  
5             require 5.006;
6              
7 13     13   71 use base 'Exporter';
  13         30  
  13         1195  
8 13     13   1213 use CGI::Application;
  13         8619  
  13         375  
9 13     13   14582 use Config::Context;
  13         170604  
  13         446  
10              
11 13     13   151 use Carp;
  13         29  
  13         3508  
12 13     13   101 use File::Spec;
  13         26  
  13         389  
13 13     13   74 use Scalar::Util qw(weaken isweak);
  13         23  
  13         1596  
14 13     13   68 use Cwd;
  13         21  
  13         763  
15              
16 13     13   183 use vars '@EXPORT';
  13         23  
  13         21697  
17             @EXPORT = qw(conf);
18              
19             our $CGIAPP_Namespace = '__CONFIG_CONTEXT';
20              
21             =head1 NAME
22              
23             CGI::Application::Plugin::Config::Context - Hierarchical, context-based configuration support for CGI::Application
24              
25             =head1 VERSION
26              
27             Version 0.18
28              
29             =cut
30              
31             our $VERSION = '0.18';
32              
33             =head1 SYNOPSIS
34              
35             =head2 Simple Access to Configuration
36              
37             In your L-based module:
38              
39             use base 'CGI::Application';
40             use CGI::Application::Plugin::Config::Context;
41              
42             sub cgiapp_init {
43             my $self = shift;
44              
45             # Set config file and other options
46             $self->conf->init(
47             file => 'app.conf',
48             driver => 'ConfigGeneral',
49             );
50             }
51              
52             sub my_run_mode {
53             my $self = shift;
54              
55             # get entire configuration
56             my %conf = $self->conf->context;
57              
58             # get entire configuration (as a reference)
59             my $conf = $self->conf->context;
60              
61             # get single config parameter
62             my $value = $self->conf->param('some_value');
63              
64             # get raw configuraion (pre-context-matching)
65             my $raw_config = $self->conf->raw;
66             my %raw_config = $self->conf->raw;
67             }
68              
69             =head2 Configuration Based on URL or Module
70              
71             You can match a configuration section to the request URL, or to the
72             module name. For instance, given the following configuration file:
73              
74             admin_area = 0
75              
76            
77             admin_area = 1
78             title = Admin Area
79            
80              
81            
82             title = Feedback Form
83            
84              
85             The configuration will depend on how the script is called:
86              
87             # URL: /cgi-bin/feedback.cgi?rm=add
88             # Module: MyApp::Feedback
89              
90             print $self->conf->param('admin_area'); # 0
91             print $self->conf->param('title'); # 'Feedback Form'
92              
93             # URL: /cgi-bin/admin/users.cgi
94             # Module: MyApp::Admin::Users
95              
96             print $self->conf->param('admin_area'); # 1
97             print $self->conf->param('title'); # 'Admin Area'
98              
99              
100             =head2 Matching Configuration based on a Virtual Host
101              
102             This module can also pick a configuration section based on the current
103             virtual-host:
104              
105             # httpd.conf
106            
107             SetEnv SITE_NAME REDSITE
108            
109              
110             # in app.conf
111            
112             background = blue
113             foreground = white
114            
115              
116            
117             background = red
118             foreground = pink
119            
120              
121            
122             background = darkgreen
123             foreground = lightgreen
124            
125              
126             =head2 Multiple configuration formats
127              
128             Supports any configuration format supported by L. As
129             of this writing, that includes the following formats:
130              
131             Apache-style syntax, via L:
132              
133            
134             admin_area = 1
135             title = Admin Area
136            
137              
138            
139             title = Feedback Form
140            
141              
142             XML, via L:
143              
144            
145             1
146             Admin Area
147            
148              
149            
150             Feedback Form
151            
152              
153             L syntax:
154              
155             AppMatch '^MyApp::Admin' {
156             admin_area = 1
157             title = Admin Area
158             }
159              
160             Location '/cgi-bin/feedback.cgi' {
161             title = Feedback Form
162             }
163              
164             Most of the examples in this document are in L syntax,
165             but can be translated into the other formats fairly easily. For more
166             information, see the L docs.
167              
168             =head1 DESCRIPTION
169              
170             This module allows you to easily access configuration data stored in
171             any of the formats supported by L: L
172             (Apache style), L and L.
173              
174             You can also automatically match configuration sections to the request
175             URL, or to the module name. This is similar to how Apache dynamically
176             selects a configuration by matching the request URL to (for instance)
177             C<< >> and C<< >> sections.
178              
179             You can also select configuration sections based on Virtual Host or by an
180             environment variable you set in an C<.htaccess> file. This allows you
181             to share a configuration file and an application between many virtual
182             hosts, each with its own unique configuration. This could be useful,
183             for instance, in providing multiple themes for a single application.
184              
185             =head2 Simple access to Configuration
186              
187             This module provides a C method to your L
188             object. First, you initialize the configuration system (typically in
189             your C method):
190              
191             $self->conf->init(
192             file => 'app.conf',
193             driver => 'ConfigGeneral',
194             );
195              
196             The configuration file is parsed at this point and the configuration is
197             available from this moment on.
198              
199             Then, within your run-modes you can retrieve configuration data:
200              
201             # get entire configuration
202             my %conf = $self->conf->context;
203             my $value = $conf{'some_value'};
204              
205             # get entire configuration (as a reference)
206             my $conf = $self->conf->context;
207             my $value = $conf->{'some_value'};
208              
209             # get single config parameter
210             my $value = $self->conf->param('some_value');
211              
212             The C method provides the configuration based on the C
213             of your application, i.e. after matching configuration sections based
214             on runtime data such as the current URL or package name.
215              
216             But you can also access the raw configuration data from before the
217             matching took place:
218              
219             # get raw configuration
220             my %conf = $self->conf->raw;
221              
222             # get raw configuration (as a reference)
223             my $conf = $self->conf->raw;
224              
225              
226             =head2 Multiple named Configurations
227              
228             You can use more than one configuration by providing a name to the
229             C method:
230              
231             $self->conf('database')->init(
232             file => 'db.conf',
233             driver => 'ConfigGeneral',
234             );
235             $self->conf('application')->init(
236             file => 'app.conf',
237             driver => 'ConfigScoped',
238             );
239              
240             ...
241              
242             my %db_config = $self->conf('database')->context;
243             my %app_config = $self->conf('application')->context;
244              
245             =head2 Configuration based on URL or Module
246              
247             Within your configuration file, you can provide different configurations
248             depending on the current URL, or on the package name of your
249             application.
250              
251             =over 4
252              
253             =item
254              
255             Matches against the C environment variable, using an I
256             match.
257              
258             # httpd.conf
259            
260             SetEnv SITE_NAME REDSITE
261            
262              
263             # in app.conf
264            
265             background = blue
266             foreground = white
267            
268              
269            
270             background = red
271             foreground = pink
272            
273              
274            
275             background = darkgreen
276             foreground = lightgreen
277            
278              
279             You can name your sections something other than C<< >>, and
280             you can use a different environment variable than C. See
281             L, below.
282              
283             =item
284              
285             Matches the Package name of your application module, for instance:
286              
287            
288             ...
289            
290              
291             The match is performed hierarchically, like a filesystem path, except
292             using C<::> as a delimiter, instead of C. The match is tied to the
293             beginning of the package name, just like absolute paths. For instance,
294             given the section:
295              
296            
297             ...
298            
299              
300             the packages C and C would match, but
301             the packages C and C would not.
302              
303             =item
304              
305             Matches the package name of your application module, using a regular
306             expression. The expression is not tied to the start of the string. For
307             instance, given the section:
308              
309            
310             ...
311            
312              
313             The following packages would all match: C, C,
314             C, C, C.
315              
316             =item
317              
318             Matches hierarchically against the request URI, including the path and
319             the C components, but I the scheme, host, port and
320             query string.
321              
322             So, for instance with the following URL:
323              
324             http://bookstore.example.com/cgi-bin/category.cgi/fiction/?rm=list
325              
326             The Location would be:
327              
328             /cgi-bin/category.cgi/fiction/
329              
330             Internally, the location is obtained by calling the C method of the
331             query object (which is usually either a L or L
332             object):
333              
334             $path = $webapp->query->url('-absolute' => 1, '-path_info' => 1);
335              
336             =item
337              
338             Matches against the request URI, using a regular expression.
339              
340             =back
341              
342             =head2 Section Merge Order
343              
344             The sections are matched in the following order:
345              
346             Site:
347             Package Name: and
348             URL: and
349              
350             When there is more than one matching section at the same level of
351             priority (e.g. two C<< >> sections, or both an C<< >>
352             and an C<< >> section), then the sections are merged in the
353             order of shortest match first.
354              
355             Values in sections matched later override the values in sections matched
356             earlier.
357              
358             The idea is that the longer matches are more specific and should have
359             priority, and that URIs are more specific than Module names.
360              
361             =head2 Section Nesting
362              
363             The sections can be nested inside each other. For instance:
364              
365            
366            
367             admin_books = 1
368            
369            
370              
371            
372            
373             admin_records = 1
374            
375            
376              
377            
378            
379            
380            
381              
382              
383             By default, the sections can be nested up to two levels deep. This
384             alows for C sections within C sections and I.
385             You can change this by setting the L parameter to
386             L.
387              
388             B there is limited support for this kind of nesting when using
389             L format files. See the documentation in
390             L for details.
391              
392             =head2 Merging Configuration Values into your Template
393              
394             You can easily pass values from your configuration files directly to
395             your templates. This allows you to associate HTML titles with URLs,
396             or keep text like copyright notices in your config file instead of your
397             templates:
398              
399             copyright_notice = Copyright (C) 1492 Christopher Columbus
400              
401            
402             title = "Manifest Destiny, Inc. - About Us"
403            
404              
405            
406             title = "Manifest Destiny, Inc. - Contact Us"
407            
408              
409             If you use L, you use the associate method when you load
410             the template:
411              
412             $self->load_template(
413             'template.tmpl',
414             'associate' => $self->conf,
415             );
416              
417             If you use L (via the L
418             module), you can accomplish the same thing by providing a custom
419             tt_pre_process method:
420              
421             sub tt_pre_process {
422             my $self = shift;
423             my $template = shift;
424             my $template_params = shift;
425              
426             my $config = $self->conf->context
427             foreach (keys %$config) {
428             unless (exists $template_params->{$_}) {
429             $template_params->{$_} = $config->{$_};
430             }
431             }
432             }
433              
434              
435             I
436             I
437             I
438             I
439              
440              
441             =head1 METHODS
442              
443             =cut
444              
445             # The 'conf' method is the only sub exported into the cgiapp namespace all
446             # other methods are called through the object returned by this method.
447             #
448             # 'conf' checks to see if an object of the requested name (or the default,
449             # unnamed object) already exists in the webapp object.
450             #
451             # If it exists it returns a reference to it
452             #
453             # If it doesn't exist, it creates it and returns a reference to it
454             #
455             #
456             # Note that at the moment, subclasses of this plugin are probably not
457             # possible because of the call to __PACKAGE__->new.
458              
459              
460             sub conf {
461 100     100 0 484990 my ($self, $conf_name) = @_;
462              
463 100 100       495 if (defined $conf_name) {
464             # Named config
465 76 100       345 if (not exists $self->{$CGIAPP_Namespace}->{'__NAMED_CONFIGS'}->{$conf_name}) {
466 28         239 $self->{$CGIAPP_Namespace}->{'__NAMED_CONFIGS'}->{$conf_name} = __PACKAGE__->_new($self, $conf_name);
467              
468             }
469 76         845 return $self->{$CGIAPP_Namespace}->{'__NAMED_CONFIGS'}->{$conf_name};
470             }
471             else {
472             # Default config
473 24 100       137 if (not exists $self->{$CGIAPP_Namespace}->{'__DEFAULT_CONFIG'}) {
474 12         97 $self->{$CGIAPP_Namespace}->{'__DEFAULT_CONFIG'} = __PACKAGE__->_new($self);
475             }
476 24         186 return $self->{$CGIAPP_Namespace}->{'__DEFAULT_CONFIG'};
477             }
478             }
479              
480             sub _new {
481 40     40   107 my ($proto, $webapp, $conf_name) = @_;
482              
483 40   33     256 my $class = ref $proto || $proto;
484              
485 40         81 my $package = ref $webapp;
486              
487 40         447 my $self = {
488             '__CONFIG_NAME' => $conf_name,
489             '__CALLERS_PACKAGE' => $package,
490             '__CGIAPP_OBJ' => $webapp,
491             '__CONFIG' => undef,
492             '__RAW_CONFIG' => undef,
493             '__CONFIG_OBJ' => undef,
494             };
495              
496             # Force reference to CGI::Application object to be weak to avoid
497             # circular references
498 40         202 weaken($self->{'__CGIAPP_OBJ'});
499              
500 40         239 return bless $self, $class;
501             }
502              
503             =head2 init
504              
505             Initializes the plugin. The only required parameter is the source of
506             the configuration, either C, C or C.
507              
508             $self->conf->init(
509             file => 'app.conf',
510             );
511              
512             The other paramters are described below:
513              
514             =over 4
515              
516             =item file
517              
518             The path to the configuration file to be parsed.
519              
520             =item string
521              
522             A string containing configuration data to be parsed.
523              
524             =item hash
525              
526             A Perl data structure containing containing the pre-parsed config data.
527              
528             =item driver
529              
530             Which L driver should parse the config. Currently
531             supported drivers are:
532              
533             driver module name
534             ------ -----------
535             ConfigGeneral Config::Context::ConfigGeneral
536             ConfigScoped Config::Context::ConfigScoped
537             XMLSimple Config::Context::XMLSimple
538              
539             The default driver is C.
540              
541             =item driver_options
542              
543             Options to pass directly on to the driver. This is a multi-level hash,
544             where the top level keys are the driver names:
545              
546             my $conf = Config::Context->new(
547             driver => 'ConfigScoped',
548             driver_options => {
549             ConfigGeneral => {
550             -AutoLaunder => 1,
551             },
552             ConfigScoped = > {
553             warnings => {
554             permissions => 'off',
555             }
556             },
557             },
558             );
559              
560             In this example the options under C will be passed to the
561             C driver. (The options under C will be
562             ignored because C is not set to C<'ConfigGeneral'>.)
563              
564             =item cache_config_files
565              
566             Whether or not to cache configuration files. Enabled, by default.
567             This option is useful in a persistent environment such as C.
568             See L under L, below.
569              
570             =item stat_config
571              
572             If config file caching is enabled, this option controls how often the
573             config files are checked to see if they have changed. The default is 60
574             seconds. This option is useful in a persistent environment such as
575             C. See L under C, below.
576              
577             =item site_section_name
578              
579             Change the name of the C<< >> section to something else. For
580             instance, to use sections named C<< >>, use:
581              
582             site_section_name => 'VirtualHost'
583              
584             =item site_var
585              
586             Change the name of the C environment variable used to match
587             against C<< >> sections. For instance To change this name to
588             C, use:
589              
590             site_var => 'HTTP_HOST',
591              
592             =item nesting_depth
593              
594             The number of levels deep that sections can be nested. The default is
595             two levels deep.
596              
597             See L
, above.
598              
599             =back
600              
601             You can initialize the plugin from within your instance CGI script:
602              
603             my $app = WebApp->new();
604             $app->conf->init(file => '../../config/app.conf');
605             $app->run();
606              
607             Or you can do so from within your C method within the
608             application:
609              
610             sub cgiapp_init {
611             my $self = shift;
612             $self->conf->init(
613             file => "$ENV{DOCUMENT_ROOT}/../config/app.conf"
614             );
615             }
616              
617              
618             =cut
619              
620             sub init {
621 38     38 1 81 my $self = shift;
622              
623 38         194 my %args = @_;
624              
625 38         126 my $config = delete $args{'config'};
626 38         89 my $file = delete $args{'file'};
627 38         86 my $string = delete $args{'string'};
628              
629 38 0 33     223 if (!$config && !$file && !$string) {
      33        
630 0         0 croak "CAP::CC->init: one of 'file', 'string' or 'config' is required";
631             }
632              
633 38 100       131 my $match_sections = exists $args{'match_sections'} ? delete $args{'match_sections'} : [];
634 38 100       135 my $driver_options = exists $args{'driver_options'} ? delete $args{'driver_options'} : {};
635 38 100       330 my $cache_config_files = exists $args{'cache_config_files'} ? delete $args{'cache_config_files'} : 1;
636 38 100       118 my $stat_config = exists $args{'stat_config'} ? delete $args{'stat_config'} : 60;
637 38 50       105 my $nesting_depth = exists $args{'nesting_depth'} ? delete $args{'nesting_depth'} : 2;
638 38 100       103 my $lower_case_names = exists $args{'lower_case_names'} ? delete $args{'lower_case_names'} : 0;
639              
640 38 100       113 my $site_var = exists $args{'site_var'} ? delete $args{'site_var'} : 'SITE_NAME';
641 38 100       107 my $site_section_name = exists $args{'site_section_name'} ? delete $args{'site_section_name'} : 'Site';
642              
643              
644 38   100     156 my $driver = delete $args{'driver'} || 'ConfigGeneral';
645              
646              
647 38 50       120 if (keys %args) {
648 0         0 croak "CAP::CC: unrecognized args to init: " .(join ', ', keys %args). "\n";
649             }
650              
651 38 100       120 unless (@$match_sections) {
652 37         131 $match_sections = $self->_default_matchsections(
653             $site_section_name
654             );
655             }
656              
657 38         157 my $cgiapp = $self->{'__CGIAPP_OBJ'};
658              
659 38         337 my $cc_obj = Config::Context->new(
660             'config' => $config,
661             'file' => $file,
662             'string' => $string,
663              
664             'driver' => $driver,
665              
666             'lower_case_names' => $lower_case_names,
667              
668             'match_sections' => $match_sections,
669             'driver_options' => $driver_options,
670             'cache_config_files' => $cache_config_files,
671              
672             'stat_config' => $stat_config,
673             'nesting_depth' => $nesting_depth,
674              
675             );
676              
677 37         64974 $self->{'__CONFIG_OBJ'} = $cc_obj;
678 37         141 $self->{'__RAW_CONFIG'} = $cc_obj->raw;
679              
680 37         483 $self->{'__CONFIG'} = $cc_obj->context(
681             'env' => $ENV{$site_var},
682             'module' => $self->{'__CALLERS_PACKAGE'},
683             'path' => $cgiapp->query->url('-absolute' => 1,'-path_info' => 1),
684             );
685              
686 37         304044 $self->_set_current_config( $self->{'__CONFIG_NAME'}, $self->{'__CONFIG'}, $self->{'__RAW_CONFIG'} );
687 37         167 return $self;
688             }
689              
690             =head2 context
691              
692             Gets the entire configuration as a hash or hashref:
693              
694             my %config = $self->conf->context; # as hash
695             my $config = $self->conf->context; # as hashref
696              
697              
698             =cut
699              
700             sub context {
701 28     28 1 53 my $self = shift;
702 28 100       80 return %{ $self->{'__CONFIG'} } if wantarray;
  3         15  
703 25         85 return $self->{'__CONFIG'};
704             }
705              
706              
707             =head2 raw
708              
709             Gets the raw configuration as a hash or hashref:
710              
711             my %raw_config = $self->conf->raw; # as hash
712             my $raw_config = $self->conf->raw; # as hashref
713              
714             The raw configuration is the configuration before matching
715             has taken place. It includes all the raw config with all of the
716             C<< >>, C<< >>, etc. sections intact.
717              
718             =cut
719              
720             sub raw{
721 16     16 1 24 my $self = shift;
722 16 50       36 return %{ $self->{'__RAW_CONFIG'} } if wantarray;
  0         0  
723 16         83 return $self->{'__RAW_CONFIG'};
724             }
725              
726             =head2 param
727              
728             Allows you to retrieve individual values from the configuration.
729              
730             It behvaves like the C method in other classes, such as L,
731             L and L:
732              
733             $value = $self->conf->param('some_key');
734             @all_keys = $self->conf->param();
735              
736             =cut
737              
738             sub param {
739 14     14 1 18 my $self = shift;
740 14         19 my $config = $self->{'__CONFIG'};
741              
742 14 100       33 if (@_) {
743 13         57 return $config->{$_[0]};
744             }
745             else {
746 1         17 return keys %$config;
747             }
748             }
749              
750             =head2 get_current_context ($name)
751              
752             This is a class method which returns the current configuration object.
753              
754             my $conf = CGI::Application::Plugin::Config::Context->get_current_context;
755             print $conf->{'title'};
756              
757             my %db_conf = CGI::Application::Plugin::Config::Context->get_current_context('db');
758             print $db_conf{'username'};
759              
760             This method is most useful in situations where you don't have access to
761             the L object, such within a L class. See
762             L for an example.
763              
764             =head2 get_current_raw_config ($name)
765              
766             Same as get_current_context, but returns the raw configuration.
767              
768             =cut
769              
770             # Sets the "current config" for a given name
771             # _set_current_config($name, \%config);
772              
773             our $Default_Current_Context_Config;
774             our $Default_Current_Raw_Config;
775             our %Current_Context_Config;
776             our %Current_Raw_Config;
777              
778             sub _set_current_config {
779 37     37   92 my ($class, $name, $context_config, $raw_config) = @_;
780              
781 37 100       114 if (defined $name) {
782 26         71 $Current_Context_Config{$name} = $context_config;
783 26         68 $Current_Raw_Config{$name} = $raw_config;
784             }
785             else {
786 11         20 $Default_Current_Context_Config = $context_config;
787 11         32 $Default_Current_Raw_Config = $raw_config;
788             }
789             }
790              
791             sub get_current_context {
792 3     3 1 4934 my ($class, $name) = @_;
793              
794 3         8 my $config = {};
795              
796 3 100       8 if (defined $name) {
797 1 50       4 if (exists $Current_Context_Config{$name}) {
798 1         2 $config = $Current_Context_Config{$name};
799             }
800             else {
801 0         0 croak "CAP::CC: requested config named '$name' does not exist\n";
802             }
803             }
804             else {
805 2         3 $config = $Default_Current_Context_Config;
806             }
807              
808 3 100       14 return %$config if wantarray;
809 2         5 return $config;
810             }
811              
812             sub get_current_raw_config {
813 1     1 1 1945 my ($class, $name) = @_;
814              
815 1         3 my $config = {};
816              
817 1 50       3 if (defined $name) {
818 0 0       0 if (exists $Current_Raw_Config{$name}) {
819 0         0 $config = $Current_Raw_Config{$name};
820             }
821             else {
822 0         0 croak "CAP::CC: requested config named '$name' does not exist\n";
823             }
824             }
825             else {
826 1         3 $config = $Default_Current_Raw_Config;
827             }
828              
829 1 50       8 return %$config if wantarray;
830 0         0 return $config;
831             }
832              
833             =head1 ADVANCED USAGE
834              
835             =head2 Usage in a Persistent Environment such as mod_perl
836              
837             The following sections describe some notes about running this module
838             under mod_perl:
839              
840             =head3 Config File Caching
841              
842             L caches configuration files by default.
843              
844             Each config file is read only once when the conf object is first
845             initialized. Thereafter, on each init, the cached config is used.
846              
847             This means that in a persistent environment like mod_perl, the config
848             file is parsed on the first request, but not on subsequent requests.
849              
850             If enough time has passed (sixty seconds by default) the config file is
851             checked to see if it has changed. If it has changed, then the file is
852             reread.
853              
854             See the docs for L for details.
855              
856             =head2 Notes on Site Matching
857              
858             =head3 Renaming C<< >> or C
859              
860             Normally, the environment variable C is matched to
861             C<< >> section.
862              
863             You can change these with the L and L
864             parameters to L:
865              
866             $self->conf->init(
867             file => 'app.conf',
868             site_section_name => 'Host',
869             site_var => 'MY_HOST',
870             );
871              
872             This will match the environment variable C to the C<< >>
873             section.
874              
875             =head3 Setting C from an C<.htaccess> file or the CGI script
876              
877             Since C is just an environment variable, you can set it
878             anywhere you can set environment variables. For instance in an C<.htaccess> file:
879              
880             # .htaccess
881             SetEnv SITE_NAME bookshop
882              
883             Or even the calling CGI script:
884              
885             #!/usr/bin/perl
886              
887             use MySite::WebApp;
888              
889             $ENV{'SITE_NAME'} = 'recordshop';
890             my $app = MySite::WebApp->new();
891             $app->run();
892              
893              
894             =head2 Access to Configuration information from another Class
895              
896             You can also get at the current configuration settings from a completely
897             unrelated Perl module. This can be useful for instance if you need to
898             configure a set of L classes, and you want them to be able
899             to pick up their configuration on their own. For instance:
900              
901             # app.conf
902              
903            
904             connect_string = dbi:Pg:dbname=example
905             username = test
906             password = test
907              
908            
909             RaiseError = 1
910             AutoCommit = 1
911            
912            
913              
914              
915             # In your Class::DBI subclass
916             package My::Class::DBI::Base;
917             use base 'Class::DBI';
918              
919             sub db_Main {
920              
921             my $conf = CGI::Application::Plugin::Config::Context->get_current_context;
922              
923             my $dsn = $conf->{'database'}{'connect_string'};
924             my $user = $conf->{'database'}{'username'};
925             my $pass = $conf->{'database'}{'password'};
926             my $opts = $conf->{'database'}{'options'};
927              
928             return DBI->connect_cached($dsn, $user, $pass, $opts);
929             }
930              
931             For this example to work, you need to make sure you call
932             C<< $self->conf->init >> before you access the database through any of your
933             L objects.
934              
935             You can also call L to get access to the raw
936             configuration.
937              
938             =head2 Changing Parsing Behaviour Using Custom L
939              
940             Internally, this module uses L to parse its config
941             files. If you want to change the parsing behaviour, you can pass your
942             own L list to L. For instance, if you want to
943             allow only sections named C<< >>, with no nesting, and have these
944             matched exactly to the complete request path, you could do the
945             following:
946              
947             # app.conf
948              
949             admin_area = 0
950             user_area = 0
951              
952            
953             admin_area = 1
954            
955              
956            
957             user_area = 1
958            
959              
960              
961             # in your cgiapp_init:
962             $self->conf->init(
963             file => 'app.conf',
964             nesting_depth => 1,
965             match_sections => [
966             {
967             name => 'URL',
968             match_type => 'exact',
969             merge_priority => 0,
970             section_type => 'path',
971             },
972             ]
973             );
974              
975              
976             For reference, here is the default L:
977              
978             [
979             {
980             name => 'Site', # overridden by 'site_section_name'
981             match_type => 'exact',
982             merge_priority => 0,
983             section_type => 'env',
984             },
985             {
986             name => 'AppMatch',
987             match_type => 'regex',
988             section_type => 'module',
989             merge_priority => 1,
990             },
991             {
992             name => 'App',
993             match_type => 'path',
994             path_separator => '::',
995             section_type => 'module',
996             merge_priority => 1,
997             },
998             {
999             name => 'LocationMatch',
1000             match_type => 'regex',
1001             section_type => 'path',
1002             merge_priority => 3,
1003             },
1004             {
1005             name => 'Location',
1006             match_type => 'path',
1007             section_type => 'path',
1008             merge_priority => 3,
1009             },
1010             ],
1011              
1012             =cut
1013              
1014             sub _default_matchsections {
1015 37     37   55 my $self = shift;
1016 37         53 my $site_var_name = shift;
1017              
1018             return [
1019             {
1020 37         522 name => $site_var_name,
1021             match_type => 'exact',
1022             merge_priority => 0,
1023             section_type => 'env',
1024             },
1025             {
1026             name => 'AppMatch',
1027             match_type => 'regex',
1028             section_type => 'module',
1029             merge_priority => 1,
1030             },
1031             {
1032             name => 'App',
1033             match_type => 'path',
1034             path_separator => '::',
1035             section_type => 'module',
1036             merge_priority => 1,
1037             },
1038             {
1039             name => 'LocationMatch',
1040             match_type => 'regex',
1041             section_type => 'path',
1042             merge_priority => 3,
1043             },
1044             {
1045             name => 'Location',
1046             match_type => 'path',
1047             section_type => 'path',
1048             merge_priority => 3,
1049             },
1050             ],
1051              
1052             }
1053              
1054              
1055              
1056             =pod
1057              
1058             For each section, the L param indicates what runtime
1059             variable the section will be matched against. Here are the allowed values
1060              
1061             env: matched to the environment variable SITE_NAME (overridden by site_name_var)
1062             module: name of the Perl Module handling this request (e.g. MyApp::Users)
1063             path: path of the request, including path_info (e.g. /cgi-bin/myapp/users.cgi/some/path)
1064              
1065             You can use the above L values in your own custom
1066             L.
1067              
1068             For more information on the syntax of L, see the docs
1069             for L.
1070              
1071             =head2 Importing the 'conf' method, but using a different name.
1072              
1073             If you want to access the features of this module using a method other
1074             than C, you can do so via Anno Siegel's L
1075             module (available on CPAN).
1076              
1077             use Exporter::Renaming;
1078             use CGI::Application::Plugin::Config::Context Renaming => [ conf => custom_config_method];
1079              
1080             sub cgiapp_init {
1081             my $self = shift;
1082              
1083             # Set config file and other options
1084             $self->custom_config_method->init(
1085             file => 'app.conf',
1086             driver => 'ConfigGeneral',
1087             );
1088              
1089             my $config = $self->custom_config_method->context;
1090              
1091             # ....
1092              
1093             }
1094              
1095             =head1 AUTHOR
1096              
1097             Michael Graham, C<< >>
1098              
1099             =head1 BUGS
1100              
1101             Please report any bugs or feature requests to
1102             C, or through the web interface at
1103             L. I will be notified, and then you'll automatically
1104             be notified of progress on your bug as I make changes.
1105              
1106             =head1 ACKNOWLEDGEMENTS
1107              
1108             Thanks to the excellent examples provided by the other
1109             L plugin authors: Mark Stosberg, Michael Peters, Cees
1110             Hek and others.
1111              
1112             =head1 SEE ALSO
1113              
1114             CGI::Application
1115             Config::Context
1116             Config::Context::ConfigGeneral
1117             Config::Context::ConfigScoped
1118             Config::Context::XMLSimple
1119             CGI::Application::Plugin::Config::Simple
1120             CGI::Application::Plugin::ConfigAuto
1121              
1122             Exporter::Renaming
1123              
1124             CGI::Application::Plugin::TT
1125             Template::Toolkit
1126             HTML::Template
1127              
1128             =head1 COPYRIGHT & LICENSE
1129              
1130             Copyright 2005 Michael Graham, All Rights Reserved.
1131              
1132             This program is free software; you can redistribute it and/or modify it
1133             under the same terms as Perl itself.
1134              
1135             =cut
1136              
1137             1;