home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Component.pm < prev    next >
Encoding:
Perl POD Document  |  2003-11-12  |  15.8 KB  |  624 lines

  1. # Copyright (c) 1998-2003 by Jonathan Swartz. All rights reserved.
  2. # This program is free software; you can redistribute it and/or modify it
  3. # under the same terms as Perl itself.
  4.  
  5. package HTML::Mason::Component;
  6.  
  7. use strict;
  8. use File::Spec;
  9. use HTML::Mason::Exceptions( abbr => [qw(param_error)] );
  10. use HTML::Mason::Tools qw(absolute_comp_path);
  11. use Params::Validate qw(:all);
  12. Params::Validate::validation_options( on_fail => sub { param_error join '', @_  } );
  13.  
  14. # for weakrefs
  15. BEGIN
  16. {
  17.     my $can_weaken = 0;
  18.     if ( $] >= 5.006 )
  19.     {
  20.         require Scalar::Util;
  21.  
  22.         $can_weaken = defined &Scalar::Util::weaken;
  23.     }
  24.  
  25.     sub CAN_WEAKEN () { $can_weaken }
  26. }
  27.  
  28. use HTML::Mason::Exceptions( abbr => ['error'] );
  29. use HTML::Mason::MethodMaker
  30.     ( read_only => [ qw( code
  31.              comp_id
  32.              compiler_id
  33.              declared_args
  34.              inherit_path
  35.              inherit_start_path
  36.                          has_filter
  37.              load_time
  38.              object_size
  39.                        ) ],
  40.  
  41.       read_write => [ [ dynamic_subs_request => { isa => 'HTML::Mason::Request' } ],
  42.               [ mfu_count => { type => SCALAR } ],
  43.                       [ filter => { type => CODEREF } ],
  44.             ]
  45.       );
  46.  
  47. # for reference later
  48. # __PACKAGE__->valid_params
  49. #     (
  50. #      attr               => {type => HASHREF, default => {}, public => 0},
  51. #      code               => {type => CODEREF, public => 0, public => 0},
  52. #      load_time          => {type => SCALAR,  optional => 1, public => 0},
  53. #      declared_args      => {type => HASHREF, default => {}, public => 0},
  54. #      dynamic_subs_init  => {type => CODEREF, default => sub {}, public => 0},
  55. #      flags              => {type => HASHREF, default => {}, public => 0},
  56. #      comp_id            => {type => SCALAR,  optional => 1, public => 0},
  57. #      methods            => {type => HASHREF, default => {}, public => 0},
  58. #      mfu_count          => {type => SCALAR,  default => 0, public => 0},
  59. #      object_size        => {type => SCALAR,  default => 0, public => 0},
  60. #      parser_version     => {type => SCALAR,  optional => 1, public => 0}, # allows older components to be instantied
  61. #      compiler_id        => {type => SCALAR,  optional => 1, public => 0},
  62. #      subcomps           => {type => HASHREF, default => {}, public => 0},
  63. #     );
  64.  
  65. my %defaults = ( attr              => {},
  66.                  declared_args     => {},
  67.                  dynamic_subs_init => sub {},
  68.                  flags             => {},
  69.                  methods           => {},
  70.                  mfu_count         => 0,
  71.                  object_size       => 0,
  72.                  subcomps          => {},
  73.                );
  74. sub new
  75. {
  76.     my $class = shift;
  77.     my $self = bless { %defaults, @_ }, $class;
  78.  
  79.     # Initialize subcomponent and method properties: owner, name, and
  80.     # is_method flag.
  81.     while (my ($name,$c) = each(%{$self->{subcomps}})) {
  82.     $c->assign_subcomponent_properties($self,$name,0);
  83.     }
  84.     while (my ($name,$c) = each(%{$self->{methods}})) {
  85.     $c->assign_subcomponent_properties($self,$name,1);
  86.     }
  87.  
  88.     return $self;
  89. }
  90.  
  91. my $comp_count = 0;
  92. sub assign_runtime_properties {
  93.     my ($self, $interp, $source) = @_;
  94.     $self->interp($interp);
  95.     $self->{comp_id} = defined $source->comp_id ? $source->comp_id : "[anon ". ++$comp_count . "]";
  96.  
  97.     $self->{path} = $source->comp_path;
  98.  
  99.     $self->_determine_inheritance;
  100.  
  101.     foreach my $c (values(%{$self->{subcomps}}), values(%{$self->{methods}})) {
  102.     $c->assign_runtime_properties($interp, $source);
  103.     }
  104. }
  105.  
  106. sub _determine_inheritance {
  107.     my $self = shift;
  108.  
  109.     my $interp = $self->interp;
  110.  
  111.     # Assign inheritance properties
  112.     if (exists($self->{flags}->{inherit})) {
  113.     if (defined($self->{flags}->{inherit})) {
  114.         $self->{inherit_path} = absolute_comp_path($self->{flags}->{inherit}, $self->dir_path);
  115.     }
  116.     } elsif ( $interp->use_autohandlers ) {
  117.     if ($self->name eq $interp->autohandler_name) {
  118.         unless ($self->dir_path eq '/') {
  119.         ($self->{inherit_start_path}) = $self->dir_path =~ m,^(.*/)?.*,s
  120.         }
  121.     } else {
  122.         $self->{inherit_start_path} = $self->dir_path;
  123.     }
  124.     }
  125. }
  126.  
  127. sub run {
  128.     my $self = shift;
  129.  
  130.     $self->{mfu_count}++;
  131.  
  132.     return $self->{code}->(@_);
  133. }
  134.  
  135. sub dynamic_subs_init {
  136.     my $self = shift;
  137.  
  138.     error "cannot call a method or subcomponent from a <%shared> block"
  139.         if $self->{in_dynamic_subs_init};
  140.  
  141.     local $self->{in_dynamic_subs_init} = 1;
  142.  
  143.     $self->{dynamic_subs_hash} = $self->{dynamic_subs_init}->();
  144.     error "could not process <%shared> section (does it contain a return()?)"
  145.     unless ref($self->{dynamic_subs_hash}) eq 'HASH';
  146. }
  147.  
  148. sub run_dynamic_sub {
  149.     my ($self, $key, @args) = @_;
  150.  
  151.     error "call_dynamic: assert error - could not find code for key $key in component " . $self->title
  152.     unless exists $self->{dynamic_subs_hash}->{$key};
  153.  
  154.     return $self->{dynamic_subs_hash}->{$key}->(@args);
  155. }
  156.  
  157. # Legacy, left in for pre-0.8 obj files
  158. sub assign_subcomponent_properties {}
  159.  
  160. #
  161. # By default components are not persistent.
  162. #
  163. sub persistent { 0 }
  164.  
  165. #
  166. # Only true in Subcomponent subclass.
  167. #
  168. sub is_subcomp { 0 }
  169.  
  170. sub is_method { 0 }
  171.  
  172. #
  173. # Only true in FileBased subclass.
  174. #
  175. sub is_file_based { 0 }
  176.  
  177. #
  178. # Basic defaults for component designators: title, path, name, dir_path
  179. #
  180. sub title { return $_[0]->{comp_id} }
  181. sub name { return $_[0]->{comp_id} }
  182. sub path { return undef }
  183. sub dir_path { return undef }
  184.  
  185. #
  186. # Get all subcomps or particular subcomp by name
  187. #
  188. sub subcomps {
  189.     my ($self,$key) = @_;
  190.     if (defined($key)) {
  191.     return $self->{subcomps}->{$key};
  192.     } else {
  193.     return $self->{subcomps};
  194.     }
  195. }
  196.  
  197. #
  198. # Get all methods or particular method by name
  199. #
  200. sub methods {
  201.     my ($self,$key) = @_;
  202.     if (defined($key)) {
  203.     return $self->{methods}->{$key};
  204.     } else {
  205.     return $self->{methods};
  206.     }
  207. }
  208.  
  209. #
  210. # Get all attributes
  211. #
  212. sub attributes { $_[0]->{attr} }
  213.  
  214. #
  215. # Get attribute by name
  216. #
  217. sub attr {
  218.     my ($self,$name) = @_;
  219.     my $value;
  220.     if ($self->_locate_inherited('attr',$name,\$value)) {
  221.     return $value;
  222.     } else {
  223.     error "no attribute '$name' for component " . $self->title;
  224.     }
  225. }
  226.  
  227. sub attr_if_exists {
  228.     my ($self,$name) = @_;
  229.     my $value;
  230.     if ($self->_locate_inherited('attr',$name,\$value)) {
  231.     return $value;
  232.     } else {
  233.     return undef;
  234.     }
  235. }
  236.  
  237. #
  238. # Determine if particular attribute exists
  239. #
  240. sub attr_exists {
  241.     my ($self,$name) = @_;
  242.     return $self->_locate_inherited('attr',$name);
  243. }
  244.  
  245. #
  246. # Call method by name
  247. #
  248. sub call_method {
  249.     my ($self,$name,@args) = @_;
  250.     my $method;
  251.     if ($self->_locate_inherited('methods',$name,\$method)) {
  252.     HTML::Mason::Request->instance->comp({base_comp=>$self},$method,@args);
  253.     } else {
  254.     error "no method '$name' for component " . $self->title;
  255.     }
  256. }
  257.  
  258. #
  259. # Like call method, but return component output.
  260. #
  261. sub scall_method {
  262.     my ($self,$name,@args) = @_;
  263.     my $method;
  264.     if ($self->_locate_inherited('methods',$name,\$method)) {
  265.     HTML::Mason::Request->instance->scomp({base_comp=>$self},$method,@args);
  266.     } else {
  267.     error "no method '$name' for component " . $self->title;
  268.     }
  269. }
  270.  
  271. #
  272. # Determine if particular method exists
  273. #
  274. sub method_exists {
  275.     my ($self,$name) = @_;
  276.     return $self->_locate_inherited('methods',$name);
  277. }
  278.  
  279. #
  280. # Locate a component slot element following inheritance path
  281. #
  282. sub _locate_inherited {
  283.     my ($self,$field,$key,$ref) = @_;
  284.     my $count = 0;
  285.     for (my $comp = $self; $comp; $comp = $comp->parent) {
  286.     if (exists($comp->{$field}->{$key})) {
  287.         $$ref = $comp->{$field}->{$key} if $ref;
  288.         return 1;
  289.     }
  290.     error "inheritance chain length > 32 (infinite inheritance loop?)"
  291.         if ++$count > 32;
  292.     }
  293.     return 0;
  294. }
  295.  
  296. #
  297. # Get particular flag by name
  298. #
  299. sub flag {
  300.     my ($self,$name) = @_;
  301.     my %flag_defaults =
  302.     (
  303.      );
  304.     if (exists($self->{flags}->{$name})) {
  305.     return $self->{flags}->{$name};
  306.     } elsif (exists($flag_defaults{$name})) {
  307.     return $flag_defaults{$name};
  308.     } else {
  309.     error "invalid flag: $name";
  310.     }
  311. }
  312.  
  313. #
  314. # Return parent component according to inherit flag
  315. #
  316. sub parent {
  317.     my ($self) = @_;
  318.     my $interp = $self->interp;
  319.  
  320.     my $comp;
  321.     if ($self->inherit_path) {
  322.     $comp = $interp->load($self->inherit_path);
  323.     } elsif ($self->inherit_start_path) {
  324.     $comp = $interp->find_comp_upwards($self->inherit_start_path, $interp->autohandler_name);
  325.     }
  326.  
  327.     return $comp;
  328. }
  329.  
  330. sub interp {
  331.     my $self = shift;
  332.  
  333.     if (@_) {
  334.         validate_pos( @_, { isa => 'HTML::Mason::Interp' } );
  335.  
  336.         $self->{interp} = $_[0];
  337.  
  338.         Scalar::Util::weaken( $self->{interp} ) if CAN_WEAKEN;
  339.     } elsif ( ! defined $self->{interp} ) {
  340.         die "The Interp object that this object contains has gone out of scope.\n";
  341.     }
  342.  
  343.     return $self->{interp};
  344. }
  345.  
  346. #
  347. # Accessors for various files associated with component
  348. #
  349. sub object_file {
  350.     my $self = shift;
  351.     return $self->interp->object_file($self);
  352. }
  353.  
  354. # For backwards compatibility with 1.0x
  355. sub create_time {
  356.     my $self = shift;
  357.     return $self->load_time(@_);
  358. }
  359.  
  360. 1;
  361.  
  362. __END__
  363.  
  364. =head1 NAME
  365.  
  366. HTML::Mason::Component - Mason Component Class
  367.  
  368. =head1 SYNOPSIS
  369.  
  370.     my $comp1 = $m->current_comp;
  371.     my $comp2 = $m->callers(1);
  372.     my $comp3 = $m->fetch_comp('foo/bar');
  373.  
  374.     foreach ($comp1,$comp2,$comp3) {
  375.        print "My name is ".$_->title.".\n";
  376.     }
  377.  
  378. =head1 DESCRIPTION
  379.  
  380. Mason uses the Component class to store components loaded into
  381. memory. Components come from three distinct sources:
  382.  
  383. =over 4
  384.  
  385. =item 1
  386.  
  387. File-based: loaded from a source or object file.
  388.  
  389. =item 2
  390.  
  391. Subcomponents: embedded components defined with the C<E<lt>%defE<gt>> 
  392. or C<E<lt>%methodE<gt>> tags.
  393.  
  394. =item 3
  395.  
  396. Anonymous: created on-the-fly with the C<make_component> Interp method.
  397.  
  398. =back
  399.  
  400. Some of the methods below return different values (or nothing at all)
  401. depending on the component type.
  402.  
  403. The component API is primarily useful for introspection, e.g. "what
  404. component called me" or "does the next component take a certain
  405. argument".  You can build complex Mason sites without ever dealing
  406. directly with a component object.
  407.  
  408. =head2 CREATING AND ACCESSING COMPONENTS
  409.  
  410. Common ways to get handles on existing component objects include the
  411. L<Request-E<gt>current_comp|HTML::Mason::Request/item_current_comp>,
  412. L<Request-E<gt>callers|HTML::Mason::Request/item_callers>, and
  413. L<Request-E<gt>fetch_comp|HTML::Mason::Request/item_fetch_comp> methods.
  414.  
  415. There is no published C<new> method, because creating a component
  416. requires an Interpreter. Use the
  417. L<make_component|HTML::Mason::Interp/item_make_component> method to
  418. create a new component dynamically.
  419.  
  420. Similarly, there is no C<execute> or C<call> method, because calling a
  421. component requires a request. All of the interfaces for calling a
  422. component (<& &>, C<$m->comp>, C<$interp-E<gt>exec>)
  423. which normally take a component path will also take a component
  424. object.
  425.  
  426. =head1 METHODS
  427.  
  428. =over
  429.  
  430. =item attr (name)
  431.  
  432. Looks for the specified attribute in this component and its parents,
  433. returning the first value found. Dies with an error if not
  434. found. Attributes are declared in the C<E<lt>%attrE<gt>> section.
  435.  
  436. =item attr_if_exists (name)
  437.  
  438. This method works exactly like the one above but returns undef if the
  439. attribute does not exist.
  440.  
  441. =item attr_exists (name)
  442.  
  443. Returns true if the specified attribute exists in this component or
  444. one of its parents, undef otherwise.
  445.  
  446. =item attributes
  447.  
  448. Returns a hashref containing the attributes defined in this component,
  449. with the attribute names as keys.  This does not return attributes
  450. inherited from parent components.
  451.  
  452. =item call_method (name, args...)
  453.  
  454. Looks for the specified user-defined method in this component and its
  455. parents, calling the first one found. Dies with an error if not found.
  456. Methods are declared in the C<E<lt>%methodE<gt>> section.
  457.  
  458. =item create_time
  459.  
  460. A synonym for L<load_time|HTML::Mason::Component/item_load_time> (deprecated).
  461.  
  462. =item declared_args
  463.  
  464. Returns a reference to a hash of hashes representing the arguments
  465. declared in the C<E<lt>%argsE<gt>> section. The keys of the main hash are the
  466. variable names including prefix (e.g. C<$foo>, C<@list>). Each    
  467. secondary hash contains:
  468.  
  469. =over 4
  470.  
  471. =item *
  472.  
  473. 'default': the string specified for default value (e.g. 'fido') or undef
  474. if none specified.  Note that in general this is not the default value
  475. itself but rather a Perl expression that gets evaluated every time the
  476. component runs.
  477.  
  478. =back
  479.  
  480. For example:
  481.  
  482.   # does $comp have an argument called $fido?
  483.   if (exists($comp->declared_args->{'$fido'})) { ... }
  484.  
  485.   # does $fido have a default value?
  486.   if (defined($comp->declared_args->{'$fido'}->{default})) { ... }
  487.  
  488. =item dir_path
  489.  
  490. Returns the component's notion of a current directory, relative to the
  491. component root; this is used to resolve relative component paths. For
  492. file-based components this is the full component path minus the filename.
  493. For subcomponents this is the same as the component that defines it.
  494. Undefined for anonymous components.
  495.  
  496. =item flag (name)
  497.  
  498. Returns the value for the specified system flag.  Flags are declared
  499. in the C<E<lt>%flagsE<gt>> section and affect the behavior of the component.
  500. Unlike attributes, flags values do not get inherited from parent components.
  501.  
  502. =item is_subcomp
  503.  
  504. Returns true if this is a subcomponent of another component.  For
  505. historical reasons, this returns true for both methods and
  506. subcomponents.
  507.  
  508. =item is_method
  509.  
  510. Returns true if this is a method.
  511.  
  512. =item is_file_based
  513.  
  514. Returns true if this component was loaded from a source or object
  515. file.
  516.  
  517. =for html <a name="item_load_time"></a>
  518.  
  519. =item load_time
  520.  
  521. Returns the time (in Perl time() format) when this component object
  522. was created.
  523.  
  524. =item method_exists (name)
  525.  
  526. Returns true if the specified user-defined method exists in this
  527. component or one of its parents, undef otherwise.
  528.  
  529. =item methods
  530.  
  531. This method works exactly like the
  532. L<subcomps|HTML::Mason::Component/item_subcomps> method, but it
  533. returns methods, not subcomponents.  This does not return methods
  534. inherited from parent components.
  535.  
  536. Methods are declared in C<E<lt>%methodE<gt>> sections.
  537.  
  538. =item name
  539.  
  540. Returns a short name of the component.  For file-based components this
  541. is the filename without the path. For subcomponents this is the name
  542. specified in C<E<lt>%defE<gt>>. Undefined for anonymous components.
  543.  
  544. =item object_file
  545.  
  546. Returns the object filename for this component.
  547.  
  548. =item owner
  549.  
  550. Defined only for subcomponents; returns the component that this
  551. subcomponent was defined in.
  552.  
  553. =item parent
  554.  
  555. Returns the parent of this component for inheritance purposes, by
  556. default the nearest C<autohandler> in or above the component's directory.
  557. Can be changed via the C<inherit> flag.
  558.  
  559. =item path
  560.  
  561. Returns the entire path of this component, relative to the component root.
  562.  
  563. =item scall_method (name, args...)
  564.  
  565. Like L<item_call_method|call_method>, but returns the method output as
  566. a string instead of printing it. (Think sprintf versus printf.) The
  567. method's return value, if any, is discarded.
  568.  
  569. =for html <a name="item_subcomps"></a>
  570.  
  571. =item subcomps
  572.  
  573. With no arguments, returns a hashref containing the subcomponents defined
  574. in this component, with names as keys and component objects as values.
  575. With one argument, returns the subcomponent of that name
  576. or undef if no such subcomponent exists. e.g.
  577.  
  578.     if (my $subcomp = $comp->subcomps('.link')) {
  579.         ...
  580.     }
  581.  
  582. Subcomponents are declared in C<E<lt>%defE<gt>> sections.
  583.  
  584. =item title
  585.  
  586. Returns a printable string denoting this component.  It is intended to
  587. uniquely identify a component within a given interpreter although this
  588. is not 100% guaranteed. Mason uses this string in error messages,
  589. among other places.
  590.  
  591. For file-based components this is the component path.  For
  592. subcomponents this is "parent_component_path:subcomponent_name". For
  593. anonymous components this is a unique label like "[anon 17]".
  594.  
  595. =back
  596.  
  597. =head1 FILE-BASED METHODS
  598.  
  599. The following methods apply only to file-based components (those
  600. loaded from source or object files). They return undef for other
  601. component types.
  602.  
  603. =over
  604.  
  605. =item source_file
  606.  
  607. Returns the source filename for this component.
  608.  
  609. =item source_dir
  610.  
  611. Returns the directory of the source filename for this component.
  612.  
  613. =back
  614.  
  615. =head1 SEE ALSO
  616.  
  617. L<HTML::Mason|HTML::Mason>,
  618. L<HTML::Mason::Devel|HTML::Mason::Devel>,
  619. L<HTML::Mason::Request|HTML::Mason::Request>
  620.  
  621. =cut
  622.