3 # $Id: Info.pm,v 1.1 2004-04-29 09:21:28 ivan Exp $
7 App::Info - Information about software packages on a system
11 use App::Info::Category::FooApp;
13 my $app = App::Info::Category::FooApp->new;
15 if ($app->installed) {
16 print "App name: ", $app->name, "\n";
17 print "Version: ", $app->version, "\n";
18 print "Bin dir: ", $app->bin_dir, "\n";
20 print "App not installed on your system. :-(\n";
25 App::Info is an abstract base class designed to provide a generalized
26 interface for subclasses that provide metadata about software packages
27 installed on a system. The idea is that these classes can be used in Perl
28 application installers in order to determine whether software dependencies
29 have been fulfilled, and to get necessary metadata about those software
32 App::Info provides an event model for handling events triggered by App::Info
33 subclasses. The events are classified as "info", "error", "unknown", and
34 "confirm" events, and multiple handlers may be specified to handle any or all
35 of these event types. This allows App::Info clients to flexibly handle events
36 in any way they deem necessary. Implementing new event handlers is
37 straight-forward, and use the triggering of events by App::Info subclasses is
38 likewise kept easy-to-use.
40 A few L<sample subclasses|"SEE ALSO"> are provided with the distribution, but
41 others are invited to write their own subclasses and contribute them to the
42 CPAN. Contributors are welcome to extend their subclasses to provide more
43 information relevant to the application for which data is to be provided (see
44 L<App::Info::HTTPD::Apache|App::Info::HTTPD::Apache> for an example), but are
45 encouraged to, at a minimum, implement the abstract methods defined here and
46 in the category abstract base classes (e.g.,
47 L<App::Info::HTTPD|App::Info::HTTPD> and L<App::Info::Lib|App::Info::Lib>).
48 See L<Subclassing|"SUBCLASSING"> for more information on implementing new
55 use App::Info::Handler;
56 use App::Info::Request;
57 use vars qw($VERSION);
61 ##############################################################################
62 ##############################################################################
63 # This code ref is used by the abstract methods to throw an exception when
64 # they're called directly.
66 my ($caller, $meth) = @_;
67 $caller = ref $caller || $caller;
68 if ($caller eq __PACKAGE__) {
69 $meth = __PACKAGE__ . '::' . $meth;
70 Carp::croak(__PACKAGE__ . " is an abstract base class. Attempt to " .
71 " call non-existent method $meth");
73 Carp::croak("Class $caller inherited from the abstract base class " .
74 __PACKAGE__ . ", but failed to redefine the $meth() " .
75 "method. Attempt to call non-existent method " .
80 ##############################################################################
81 # This code reference is used by new() and the on_* error handler methods to
82 # set the error handlers.
83 my $set_handlers = sub {
85 # Default is to do nothing.
86 return [] unless $on_key;
87 my $ref = ref $on_key;
89 $on_key = [$on_key] unless $ref eq 'ARRAY';
90 # Make sure they're all handlers.
91 foreach my $h (@$on_key) {
93 Carp::croak("$r object is not an App::Info::Handler")
94 unless UNIVERSAL::isa($h, 'App::Info::Handler');
96 # Look up the handler.
97 $h = App::Info::Handler->new( key => $h);
103 # Look up the handler.
104 return [ App::Info::Handler->new( key => $on_key) ];
108 ##############################################################################
109 ##############################################################################
113 This section documents the public interface of App::Info.
119 my $app = App::Info::Category::FooApp->new(@params);
121 Constructs an App::Info object and returns it. The @params arguments define
122 how the App::Info object will respond to certain events, and correspond to
123 their like-named methods. See the L<"Event Handler Object Methods"> section
124 for more information on App::Info events and how to handle them. The
125 parameters to C<new()> for the different types of App::Info events are:
139 When passing event handlers to C<new()>, the list of handlers for each type
140 should be an anonymous array, for example:
142 my $app = App::Info::Category::FooApp->new( on_info => \@handlers );
148 my $class = ref $pkg || $pkg;
149 # Fail if the method isn't overridden.
150 $croak->($pkg, 'new') if $class eq __PACKAGE__;
153 for (qw(on_error on_unknown on_info on_confirm)) {
154 $p{$_} = $set_handlers->($p{$_});
158 return bless \%p, $class;
161 ##############################################################################
162 ##############################################################################
164 =head2 Metadata Object Methods
166 These are abstract methods in App::Info and must be provided by its
167 subclasses. They provide the essential metadata of the software package
168 supported by the App::Info subclass.
172 my $key_name = $app->key_name;
174 Returns a string that uniquely identifies the software for which the App::Info
175 subclass provides data. This value should be unique across all App::Info
176 classes. Typically, it's simply the name of the software.
180 sub key_name { $croak->(shift, 'key_name') }
184 if ($app->installed) {
185 print "App is installed.\n"
187 print "App is not installed.\n"
190 Returns a true value if the application is installed, and a false value if it
195 sub installed { $croak->(shift, 'installed') }
197 ##############################################################################
201 my $name = $app->name;
203 Returns the name of the application.
207 sub name { $croak->(shift, 'name') }
209 ##############################################################################
213 my $version = $app->version;
215 Returns the full version number of the application.
219 ##############################################################################
221 sub version { $croak->(shift, 'version') }
225 my $major_version = $app->major_version;
227 Returns the major version number of the application. For example, if
228 C<version()> returns "7.1.2", then this method returns "7".
232 sub major_version { $croak->(shift, 'major_version') }
234 ##############################################################################
238 my $minor_version = $app->minor_version;
240 Returns the minor version number of the application. For example, if
241 C<version()> returns "7.1.2", then this method returns "1".
245 sub minor_version { $croak->(shift, 'minor_version') }
247 ##############################################################################
251 my $patch_version = $app->patch_version;
253 Returns the patch version number of the application. For example, if
254 C<version()> returns "7.1.2", then this method returns "2".
258 sub patch_version { $croak->(shift, 'patch_version') }
260 ##############################################################################
264 my $bin_dir = $app->bin_dir;
266 Returns the full path the application's bin directory, if it exists.
270 sub bin_dir { $croak->(shift, 'bin_dir') }
272 ##############################################################################
276 my $inc_dir = $app->inc_dir;
278 Returns the full path the application's include directory, if it exists.
282 sub inc_dir { $croak->(shift, 'inc_dir') }
284 ##############################################################################
288 my $lib_dir = $app->lib_dir;
290 Returns the full path the application's lib directory, if it exists.
294 sub lib_dir { $croak->(shift, 'lib_dir') }
296 ##############################################################################
300 my $so_lib_dir = $app->so_lib_dir;
302 Returns the full path the application's shared library directory, if it
307 sub so_lib_dir { $croak->(shift, 'so_lib_dir') }
309 ##############################################################################
313 my $home_url = $app->home_url;
315 The URL for the software's home page.
319 sub home_url { $croak->(shift, 'home_url') }
321 ##############################################################################
325 my $download_url = $app->download_url;
327 The URL for the software's download page.
331 sub download_url { $croak->(shift, 'download_url') }
333 ##############################################################################
334 ##############################################################################
336 =head2 Event Handler Object Methods
338 These methods provide control over App::Info event handling. Events can be
339 handled by one or more objects of subclasses of App::Info::Handler. The first
340 to return a true value will be the last to execute. This approach allows
341 handlers to be stacked, and makes it relatively easy to create new handlers.
342 L<App::Info::Handler|App::Info::Handler> for information on writing event
345 Each of the event handler methods takes a list of event handlers as its
346 arguments. If none are passed, the existing list of handlers for the relevant
347 event type will be returned. If new handlers are passed in, they will be
350 The event handlers may be specified as one or more objects of the
351 App::Info::Handler class or subclasses, as one or more strings that tell
352 App::Info construct such handlers itself, or a combination of the two. The
353 strings can only be used if the relevant App::Info::Handler subclasses have
354 registered strings with App::Info. For example, the App::Info::Handler::Print
355 class included in the App::Info distribution registers the strings "stderr"
356 and "stdout" when it starts up. These strings may then be used to tell
357 App::Info to construct App::Info::Handler::Print objects that print to STDERR
358 or to STDOUT, respectively. See the App::Info::Handler subclasses for what
359 strings they register with App::Info.
363 my @handlers = $app->on_info;
364 $app->on_info(@handlers);
366 Info events are triggered when the App::Info subclass wants to send an
367 informational status message. By default, these events are ignored, but a
368 common need is for such messages to simply print to STDOUT. Use the
369 L<App::Info::Handler::Print|App::Info::Handler::Print> class included with the
370 App::Info distribution to have info messages print to STDOUT:
372 use App::Info::Handler::Print;
373 $app->on_info('stdout');
375 my $stdout_handler = App::Info::Handler::Print->new('stdout');
376 $app->on_info($stdout_handler);
382 $self->{on_info} = $set_handlers->(\@_) if @_;
383 return @{ $self->{on_info} };
388 my @handlers = $app->on_error;
389 $app->on_error(@handlers);
391 Error events are triggered when the App::Info subclass runs into an unexpected
392 but not fatal problem. (Note that fatal problems will likely throw an
393 exception.) By default, these events are ignored. A common way of handling
394 these events is to print them to STDERR, once again using the
395 L<App::Info::Handler::Print|App::Info::Handler::Print> class included with the
396 App::Info distribution:
398 use App::Info::Handler::Print;
399 my $app->on_error('stderr');
401 my $stderr_handler = App::Info::Handler::Print->new('stderr');
402 $app->on_error($stderr_handler);
404 Another approach might be to turn such events into fatal exceptions. Use the
405 included L<App::Info::Handler::Carp|App::Info::Handler::Carp> class for this
408 use App::Info::Handler::Carp;
409 my $app->on_error('croak');
411 my $croaker = App::Info::Handler::Carp->new('croak');
412 $app->on_error($croaker);
418 $self->{on_error} = $set_handlers->(\@_) if @_;
419 return @{ $self->{on_error} };
424 my @handlers = $app->on_unknown;
425 $app->on_uknown(@handlers);
427 Unknown events are trigged when the App::Info subclass cannot find the value
428 to be returned by a method call. By default, these events are ignored. A
429 common way of handling them is to have the application prompt the user for the
430 relevant data. The App::Info::Handler::Prompt class included with the
431 App::Info distribution can do just that:
433 use App::Info::Handler::Prompt;
434 my $app->on_unknown('prompt');
436 my $prompter = App::Info::Handler::Prompt;
437 $app->on_unknown($prompter);
439 See L<App::Info::Handler::Prompt|App::Info::Handler::Prompt> for information
446 $self->{on_unknown} = $set_handlers->(\@_) if @_;
447 return @{ $self->{on_unknown} };
452 my @handlers = $app->on_confirm;
453 $app->on_confirm(@handlers);
455 Confirm events are triggered when the App::Info subclass has found an
456 important piece of information (such as the location of the executable it'll
457 use to collect information for the rest of its methods) and wants to confirm
458 that the information is correct. These events will most often be triggered
459 during the App::Info subclass object construction. Here, too, the
460 App::Info::Handler::Prompt class included with the App::Info distribution can
463 use App::Info::Handler::Prompt;
464 my $app->on_confirm('prompt');
466 my $prompter = App::Info::Handler::Prompt;
467 $app->on_confirm($prompter);
473 $self->{on_confirm} = $set_handlers->(\@_) if @_;
474 return @{ $self->{on_confirm} };
477 ##############################################################################
478 ##############################################################################
482 As an abstract base class, App::Info is not intended to be used directly.
483 Instead, you'll use concrete subclasses that implement the interface it
484 defines. These subclasses each provide the metadata necessary for a given
485 software package, via the interface outlined above (plus any additional
486 methods the class author deems sensible for a given application).
488 This section describes the facilities App::Info provides for subclassing. The
489 goal of the App::Info design has been to make subclassing straight-forward, so
490 that developers can focus on gathering the data they need for their
491 application and minimize the work necessary to handle unknown values or to
492 confirm values. As a result, there are essentially three concepts that
493 developers need to understand when subclassing App::Info: organization,
494 utility methods, and events.
498 The organizational idea behind App::Info is to name subclasses by broad
499 software categories. This approach allows the categories themselves to
500 function as abstract base classes that extend App::Info, so that they can
501 specify more methods for all of their base classes to implement. For example,
502 App::Info::HTTPD has specified the C<httpd_root()> abstract method that its
503 subclasses must implement. So as you get ready to implement your own subclass,
504 think about what category of software you're gathering information about.
505 New categories can be added as necessary.
507 =head2 Utility Methods
509 Once you've decided on the proper category, you can start implementing your
510 App::Info concrete subclass. As you do so, take advantage of App::Info::Util,
511 wherein I've tried to encapsulate common functionality to make subclassing
512 easier. I found that most of what I was doing repetitively was looking for
513 files and directories, and searching through files. Thus, App::Info::Util
514 subclasses L<File::Spec|File::Spec> in order to offer easy access to
515 commonly-used methods from that class, e.g., C<path()>. Plus, it has several
516 of its own methods to assist you in finding files and directories in lists of
517 files and directories, as well as methods for searching through files and
518 returning the values found in those files. See
519 L<App::Info::Util|App::Info::Util> for more information, and the App::Info
520 subclasses in this distribution for usage examples.
522 I recommend the use of a package-scoped lexical App::Info::Util object. That
523 way it's nice and handy when you need to carry out common tasks. If you find
524 you're doing something over and over that's not already addressed by an
525 App::Info::Util method, consider submitting a patch to App::Info::Util to add
526 the functionality you need.
530 Use the methods described below to trigger events. Events are designed to
531 provide a simple way for App::Info subclass developers to send status messages
532 and errors, to confirm data values, and to request a value when the class
533 caonnot determine a value itself. Events may optionally be handled by module
534 users who assign App::Info::Handler subclass objects to your App::Info
535 subclass object using the event handling methods described in the L<"Event
536 Handler Object Methods"> section.
540 ##############################################################################
541 # This code reference is used by the event methods to manage the stack of
542 # event handlers that may be available to handle each of the events.
544 my ($self, $meth, $params) = @_;
546 # Sanity check. We really want to keep control over this.
547 Carp::croak("Cannot call protected method $meth()")
548 unless UNIVERSAL::isa($self, scalar caller(1));
550 # Create the request object.
551 $params->{type} ||= $meth;
552 my $req = App::Info::Request->new(%$params);
554 # Do the deed. The ultimate handling handler may die.
555 foreach my $eh (@{$self->{"on_$meth"}}) {
556 last if $eh->handler($req);
563 ##############################################################################
567 $self->info(@message);
569 Use this method to display status messages for the user. You may wish to use
570 it to inform users that you're searching for a particular file, or attempting
571 to parse a file or some other resource for the data you need. For example, a
572 common use might be in the object constructor: generally, when an App::Info
573 object is created, some important initial piece of information is being
574 sought, such as an executable file. That file may be in one of many locations,
575 so it makes sense to let the user know that you're looking for it:
577 $self->info("Searching for executable");
579 Note that, due to the nature of App::Info event handlers, your informational
580 message may be used or displayed any number of ways, or indeed not at all (as
581 is the default behavior).
583 The C<@message> will be joined into a single string and stored in the
584 C<message> attribute of the App::Info::Request object passed to info event
591 # Execute the handler sequence.
592 my $req = $handler->($self, 'info', { message => join '', @_ });
595 ##############################################################################
599 $self->error(@error);
601 Use this method to inform the user that something unexpected has happened. An
602 example might be when you invoke another program to parse its output, but it's
603 output isn't what you expected:
605 $self->error("Unable to parse version from `/bin/myapp -c`");
607 As with all events, keep in mind that error events may be handled in any
608 number of ways, or not at all.
610 The C<@erorr> will be joined into a single string and stored in the C<message>
611 attribute of the App::Info::Request object passed to error event handlers. If
612 that seems confusing, think of it as an "error message" rather than an "error
619 # Execute the handler sequence.
620 my $req = $handler->($self, 'error', { message => join '', @_ });
623 ##############################################################################
627 my $val = $self->unknown(@params);
629 Use this method when a value is unknown. This will give the user the option --
630 assuming the appropriate handler handles the event -- to provide the needed
631 data. The value entered will be returned by C<unknown()>. The parameters are
638 The C<key> parameter uniquely identifies the data point in your class, and is
639 used by App::Info to ensure that an unknown event is handled only once, no
640 matter how many times the method is called. The same value will be returned by
641 subsequent calls to C<unknown()> as was returned by the first call, and no
642 handlers will be activated. Typical values are "version" and "lib_dir".
646 The C<prompt> parameter is the prompt to be displayed should an event handler
647 decide to prompt for the appropriate value. Such a prompt might be something
648 like "Path to your httpd executable?". If this parameter is not provided,
649 App::Info will construct one for you using your class' C<key_name()> method
650 and the C<key> parameter. The result would be something like "Enter a valid
651 FooApp version". The C<prompt> parameter value will be stored in the
652 C<message> attribute of the App::Info::Request object passed to event
657 Assuming a handler has collected a value for your unknown data point, it might
658 make sense to validate the value. For example, if you prompt the user for a
659 directory location, and the user enters one, it makes sense to ensure that the
660 directory actually exists. The C<callback> parameter allows you to do this. It
661 is a code reference that takes the new value or values as its arguments, and
662 returns true if the value is valid, and false if it is not. For the sake of
663 convenience, the first argument to the callback code reference is also stored
664 in C<$_> .This makes it easy to validate using functions or operators that,
665 er, operate on C<$_> by default, but still allows you to get more information
666 from C<@_> if necessary. For the directory example, a good callback might be
667 C<sub { -d }>. The C<callback> parameter code reference will be stored in the
668 C<callback> attribute of the App::Info::Request object passed to event
673 The error parameter is the error message to display in the event that the
674 C<callback> code reference returns false. This message may then be used by the
675 event handler to let the user know what went wrong with the data she entered.
676 For example, if the unknown value was a directory, and the user entered a
677 value that the C<callback> identified as invalid, a message to display might
678 be something like "Invalid directory path". Note that if the C<error>
679 parameter is not provided, App::Info will supply the generic error message
680 "Invalid value". This value will be stored in the C<error> attribute of the
681 App::Info::Request object passed to event handlers.
685 This may be the event method you use most, as it should be called in every
686 metadata method if you cannot provide the data needed by that method. It will
687 typically be the last part of the method. Here's an example demonstrating each
688 of the above arguments:
690 my $dir = $self->unknown( key => 'lib_dir',
691 prompt => "Enter lib directory path",
692 callback => sub { -d },
693 error => "Not a directory");
698 my ($self, %params) = @_;
699 my $key = delete $params{key}
700 or Carp::croak("No key parameter passed to unknown()");
701 # Just return the value if we've already handled this value. Ideally this
703 return $self->{__unknown__}{$key} if exists $self->{__unknown__}{$key};
705 # Create a prompt and error message, if necessary.
706 $params{message} = delete $params{prompt} ||
707 "Enter a valid " . $self->key_name . " $key";
708 $params{error} ||= 'Invalid value';
710 # Execute the handler sequence.
711 my $req = $handler->($self, "unknown", \%params);
713 # Mark that we've provided this value and then return it.
714 $self->{__unknown__}{$key} = $req->value;
715 return $self->{__unknown__}{$key};
718 ##############################################################################
722 my $val = $self->confirm(@params);
724 This method is very similar to C<unknown()>, but serves a different purpose.
725 Use this method for significant data points where you've found an appropriate
726 value, but want to ensure it's really the correct value. A "significant data
727 point" is usually a value essential for your class to collect metadata values.
728 For example, you might need to locate an executable that you can then call to
729 collect other data. In general, this will only happen once for an object --
730 during object construction -- but there may be cases in which it is needed
731 more than that. But hopefully, once you've confirmed in the constructor that
732 you've found what you need, you can use that information to collect the data
733 needed by all of the metadata methods and can assume that they'll be right
734 because that first, significant data point has been confirmed.
736 Other than where and how often to call C<confirm()>, its use is quite similar
737 to that of C<unknown()>. Its parameters are as follows:
743 Same as for C<unknown()>, a string that uniquely identifies the data point in
744 your class, and ensures that the event is handled only once for a given key.
745 The same value will be returned by subsequent calls to C<confirm()> as was
746 returned by the first call for a given key.
750 Same as for C<unknown()>. Although C<confirm()> is called to confirm a value,
751 typically the prompt should request the relevant value, just as for
752 C<unknown()>. The difference is that the handler I<should> use the C<value>
753 parameter as the default should the user not provide a value. The C<prompt>
754 parameter will be stored in the C<message> attribute of the App::Info::Request
755 object passed to event handlers.
759 The value to be confirmed. This is the value you've found, and it will be
760 provided to the user as the default option when they're prompted for a new
761 value. This value will be stored in the C<value> attribute of the
762 App::Info::Request object passed to event handlers.
766 Same as for C<unknown()>. Because the user can enter data to replace the
767 default value provided via the C<value> parameter, you might want to validate
768 it. Use this code reference to do so. The callback will be stored in the
769 C<callback> attribute of the App::Info::Request object passed to event
774 Same as for C<unknown()>: an error message to display in the event that a
775 value entered by the user isn't validated by the C<callback> code reference.
776 This value will be stored in the C<error> attribute of the App::Info::Request
777 object passed to event handlers.
781 Here's an example usage demonstrating all of the above arguments:
783 my $exe = $self->confirm( key => 'shell',
784 prompt => 'Path to your shell?',
786 callback => sub { -x },
787 error => 'Not an executable');
793 my ($self, %params) = @_;
794 my $key = delete $params{key}
795 or Carp::croak("No key parameter passed to confirm()");
796 return $self->{__confirm__}{$key} if exists $self->{__confirm__}{$key};
798 # Create a prompt and error message, if necessary.
799 $params{message} = delete $params{prompt} ||
800 "Enter a valid " . $self->key_name . " $key";
801 $params{error} ||= 'Invalid value';
803 # Execute the handler sequence.
804 my $req = $handler->($self, "confirm", \%params);
806 # Mark that we've confirmed this value.
807 $self->{__confirm__}{$key} = $req->value;
809 return $self->{__confirm__}{$key}
815 =head2 Event Examples
817 Below I provide some examples demonstrating the use of the event methods.
818 These are meant to emphasize the contexts in which it's appropriate to use
821 Let's start with the simplest, first. Let's say that to find the version
822 number for an application, you need to search a file for the relevant data.
823 Your App::Info concrete subclass might have a private method that handles this
824 work, and this method is the appropriate place to use the C<info()> and, if
825 necessary, C<error()> methods.
830 # Try to find the revelant file. We cover this method below.
831 # Just return if we cant' find it.
832 my $file = $self->_find_file('version.conf') or return;
834 # Send a status message.
835 $self->info("Searching '$file' file for version");
837 # Search the file. $util is an App::Info::Util object.
838 my $ver = $util->search_file($file, qr/^Version\s+(.*)$/);
840 # Trigger an error message, if necessary. We really think we'll have the
841 # value, but we have to cover our butts in the unlikely event that we're
843 $self->error("Unable to find version in file '$file'") unless $ver;
845 # Return the version number.
849 Here we've used the C<info()> method to display a status message to let the
850 user know what we're doing. Then we used the C<error()> method when something
851 unexpected happened, which in this case was that we weren't able to find the
852 version number in the file.
854 Note the C<_find_file()> method we've thrown in. This might be a method that
855 we call whenever we need to find a file that might be in one of a list of
856 directories. This method, too, will be an appropriate place for an C<info()>
857 method call. But rather than call the C<error()> method when the file can't be
858 found, you might want to give an event handler a chance to supply that value
859 for you. Use the C<unknown()> method for a case such as this:
862 my ($self, $file) = @_;
864 # Send a status message.
865 $self->info("Searching for '$file' file");
867 # Look for the file. See App::Info:Utility for its interface.
868 my @paths = qw(/usr/conf /etc/conf /foo/conf);
869 my $found = $util->first_cat_path($file, @paths);
871 # If we didn't find it, trigger an unknown event to
872 # give a handler a chance to get the value.
873 $found ||= $self->unknown( key => "file_$file",
874 prompt => "Location of '$file' file?",
875 callback => sub { -f },
876 error => "Not a file");
878 # Now return the file name, regardless of whether we found it or not.
882 Note how in this method, we've tried to locate the file ourselves, but if we
883 can't find it, we trigger an unknown event. This allows clients of our
884 App::Info subclass to try to establish the value themselves by having an
885 App::Info::Handler subclass handle the event. If a value is found by an
886 App::Info::Handler subclass, it will be returned by C<unknown()> and we can
887 continue. But we can't assume that the unknown event will even be handled, and
888 thus must expect that an unknown value may remain unknown. This is why the
889 C<_find_version()> method above simply returns if C<_find_file()> doesn't
890 return a file name; there's no point in searching through a file that doesn't
893 Attentive readers may be left to wonder how to decide when to use C<error()>
894 and when to use C<unknown()>. To a large extent, this decision must be based
895 on one's own understanding of what's most appropriate. Nevertheless, I offer
896 the following simple guidelines: Use C<error()> when you expect something to
897 work and then it just doesn't (as when a file exists and should contain the
898 information you seek, but then doesn't). Use C<unknown()> when you're less
899 sure of your processes for finding the value, and also for any of the values
900 that should be returned by any of the L<metadata object methods|"Metadata
901 Object Methods">. And of course, C<error()> would be more appropriate when you
902 encounter an unexpected condition and don't think that it could be handled in
905 Now, more than likely, a method such C<_find_version()> would be called by the
906 C<version()> method, which is a metadata method mandated by the App::Info
907 abstract base class. This is an appropriate place to handle an unknown version
908 value. Indeed, every one of your metadata methods should make use of the
909 C<unknown()> method. The C<version()> method then should look something like
915 unless (exists $self->{version}) {
916 # Try to find the version number.
917 $self->{version} = $self->_find_version ||
918 $self->unknown( key => 'version',
919 prompt => "Enter the version number");
922 # Now return the version number.
923 return $self->{version};
926 Note how this method only tries to find the version number once. Any
927 subsequent calls to C<version()> will return the same value that was returned
928 the first time it was called. Of course, thanks to the C<key> parameter in the
929 call to C<unknown()>, we could have have tried to enumerate the version number
930 every time, as C<unknown()> will return the same value every time it is called
931 (as, indeed, should C<_find_version()>. But by checking for the C<version> key
932 in C<$self> ourselves, we save some of the overhead.
934 But as I said before, every metadata method should make use of the
935 C<unknown()> method. Thus, the C<major()> method might looks something like
941 unless (exists $self->{major}) {
942 # Try to get the major version from the full version number.
943 ($self->{major}) = $self->version =~ /^(\d+)\./;
944 # Handle an unknown value.
945 $self->{major} = $self->unknown( key => 'major',
946 prompt => "Enter major version",
947 callback => sub { /^\d+$/ },
948 error => "Not a number")
949 unless defined $self->{major};
952 return $self->{version};
955 Finally, the C<confirm()> method should be used to verify core pieces of data
956 that significant numbers of other methods rely on. Typically such data are
957 executables or configuration files from which will be drawn other metadata.
958 Most often, such major data points will be sought in the object constructor.
962 # Construct the object so that handlers will work properly.
963 my $self = shift->SUPER::new(@_);
965 # Try to find the executable.
966 $self->info("Searching for executable");
967 if (my $exe = $util->first_exe('/bin/myapp', '/usr/bin/myapp')) {
970 $self->confirm( key => 'binary',
971 prompt => 'Path to your executable?',
973 callback => sub { -x },
974 error => 'Not an executable');
976 # Handle an unknown value.
978 $self->unknown( key => 'binary',
979 prompt => 'Path to your executable?',
980 callback => sub { -x },
981 error => 'Not an executable');
988 By now, most of what's going on here should be quite familiar. The use of the
989 C<confirm()> method is quite similar to that of C<unknown()>. Really the only
990 difference is that the value is known, but we need verification or a new value
991 supplied if the value we found isn't correct. Such may be the case when
992 multiple copies of the executable have been installed on the system, we found
993 F</bin/myapp>, but the user may really be interested in F</usr/bin/myapp>.
994 Thus the C<confirm()> event gives the user the chance to change the value if
995 the confirm event is handled.
997 The final thing to note about this constructor is the first line:
999 my $self = shift->SUPER::new(@_);
1001 The first thing an App::Info subclass should do is execute this line to allow
1002 the super class to construct the object first. Doing so allows any event
1003 handling arguments to set up the event handlers, so that when we call
1004 C<confirm()> or C<unknown()> the event will be handled as the client expects.
1006 If we needed our subclass constructor to take its own parameter argumente, the
1007 approach is to specify the same C<key => $arg> syntax as is used by
1008 App::Info's C<new()> method. Say we wanted to allow clients of our App::Info
1009 subclass to pass in a list of alternate executable locations for us to search.
1010 Such an argument would most make sense as an array reference. So we specify
1011 that the key be C<alt_paths> and allow the user to construct an object like
1014 my $app = App::Info::Category::FooApp->new( alt_paths => \@paths );
1016 This approach allows the super class constructor arguments to pass unmolested
1017 (as long as we use unique keys!):
1019 my $app = App::Info::Category::FooApp->new( on_error => \@handlers,
1020 alt_paths => \@paths );
1022 Then, to retrieve these paths inside our C<new()> constructor, all we need do
1023 is access them directly from the object:
1025 my $self = shift->SUPER::new(@_);
1026 my $alt_paths = $self->{alt_paths};
1028 =head2 Subclassing Guidelines
1030 To summarize, here are some guidelines for subclassing App::Info.
1036 Always subclass an App::Info category subclass. This will help to keep the
1037 App::Info namespace well-organized. New categories can be added as needed.
1041 When you create the C<new()> constructor, always call C<SUPER::new(@_)>. This
1042 ensures that the event handling methods methods defined by the App::Info base
1043 classes (e.g., C<error()>) will work properly.
1047 Use a package-scoped lexical App::Info::Util object to carry out common tasks.
1048 If you find you're doing something over and over that's not already addressed
1049 by an App::Info::Util method, and you think that others might find your
1050 solution useful, consider submitting a patch to App::Info::Util to add the
1051 functionality you need. See L<App::Info::Util|App::Info::Util> for complete
1052 documentation of its interface.
1056 Use the C<info()> event triggering method to send messages to users of your
1061 Use the C<error()> event triggering method to alert users of unexpected
1062 conditions. Fatal errors should still be fatal; use C<Carp::croak()> to throw
1063 exceptions for fatal errors.
1067 Use the C<unknown()> event triggering method when a metadata or other
1068 important value is unknown and you want to give any event handlers the chance
1069 to provide the data.
1073 Use the C<confirm()> event triggering method when a core piece of data is
1074 known (such as the location of an executable in the C<new()> constructor) and
1075 you need to make sure that you have the I<correct> information.
1079 Be sure to implement B<all> of the abstract methods defined by App::Info and
1080 by your category abstract base class -- even if they don't do anything. Doing
1081 so ensures that all App::Info subclasses share a common interface, and can, if
1082 necessary, be used without regard to subclass. Any method not implemented but
1083 called on an object will generate a fatal exception.
1087 Otherwise, have fun! There are a lot of software packages for which relevant
1088 information might be collected and aggregated into an App::Info concrete
1089 subclass (witness all of the Automake macros in the world!), and folks who are
1090 knowledgeable about particular software packages or categories of software are
1091 warmly invited to contribute. As more subclasses are implemented, it will make
1092 sense, I think, to create separate distributions based on category -- or even,
1093 when necessary, on a single software package. Broader categories can then be
1094 aggregated in Bundle distributions.
1096 But I get ahead of myself...
1100 Report all bugs via the CPAN Request Tracker at
1101 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=App-Info>.
1105 David Wheeler <L<david@wheeler.net|"david@wheeler.net">>
1109 The following classes define a few software package categories in which
1110 App::Info subclasses can be placed. Check them out for ideas on how to
1111 create new category subclasses.
1115 =item L<App::Info::HTTP|App::Info::HTTPD>
1117 =item L<App::Info::RDBMS|App::Info::RDBMS>
1119 =item L<App::Info::Lib|App::Info::Lib>
1123 The following classes implement the App::Info interface for various software
1124 packages. Check them out for examples of how to implement new App::Info
1125 concrete subclasses.
1129 =item L<App::Info::HTTPD::Apache|App::Info::HTTPD::Apache>
1131 =item L<App::Info::RDBMS::PostgreSQL|App::Info::RDBMS::PostgreSQL>
1133 =item L<App::Info::Lib::Expat|App::Info::Lib::Expat>
1135 =item L<App::Info::Lib::Iconv|App::Info::Lib::Iconv>
1139 L<App::Info::Util|App::Info::Util> provides utility methods for App::Info
1142 L<App::Info::Handler|App::Info::Handler> defines an interface for event
1143 handlers to subclass. Consult its documentation for information on creating
1144 custom event handlers.
1146 The following classes implement the App::Info::Handler interface to offer some
1147 simple event handling. Check them out for examples of how to implement new
1148 App::Info::Handler subclasses.
1152 =item L<App::Info::Handler::Print|App::Info::Handler::Print>
1154 =item L<App::Info::Handler::Carp|App::Info::Handler::Carp>
1156 =item L<App::Info::Handler::Prompt|App::Info::Handler::Prompt>
1160 =head1 COPYRIGHT AND LICENSE
1162 Copyright (c) 2002, David Wheeler. All Rights Reserved.
1164 This module is free software; you can redistribute it and/or modify it under
1165 the same terms as Perl itself.