IOC::Visitor::SearchForService - Visitor for searching a IOC::Container hierarchy


IOC documentation Contained in the IOC distribution.

Index


Code Index:

NAME

Top

IOC::Visitor::SearchForService - Visitor for searching a IOC::Container hierarchy

SYNOPSIS

Top

  use IOC::Visitor::SearchForService;

DESCRIPTION

Top

This is a IOC::Visitor object used for searching a IOC::Container hierarchy.

          +------------------+
          | <<IOC::Visitor>> |
          +------------------+
                   |
                   ^
                   |
   +--------------------------------+
   | IOC::Visitor::SearchForService |
   +--------------------------------+

METHODS

Top

new ($name)

Creates a new instance which will search for a Service at a given $name. If no $name is given, than an IOC::InsufficientArguments exception is thrown.

visit ($container)

Given a $container, the invocant will attempt to locate the service with the $name (given to the constuctor) from within the $container's hierarchy.

TO DO

Top

Work on the documentation

BUGS

Top

None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it.

CODE COVERAGE

Top

I use Devel::Cover to test the code coverage of my tests, see the CODE COVERAGE section of IOC for more information.

SEE ALSO

Top

AUTHOR

Top

stevan little, <stevan@iinteractive.com>

COPYRIGHT AND LICENSE

Top


IOC documentation Contained in the IOC distribution.

package IOC::Visitor::SearchForService;

use strict;
use warnings;

our $VERSION = '0.03';

use Scalar::Util qw(blessed);

use IOC::Interfaces;
use IOC::Exceptions;

use base 'IOC::Visitor';

sub new {
    my ($_class, $service_name) = @_;
    ($service_name) 
        || throw IOC::InsufficientArguments "You must provide a name of a service to find";
    my $class = ref($_class) || $_class;
    my $visitor = {
        service_to_find => $service_name
        };
    bless($visitor, $class);
    return $visitor;
}

sub visit {
    my ($self, $container) = @_;
    (blessed($container) && $container->isa('IOC::Container'))
        || throw IOC::InsufficientArguments "You must provide an IOC::Container object to search";
    my $service_to_find = $self->{service_to_find};
    return $self->_recursiveSearch($container, $service_to_find);
}

sub _recursiveSearch {
    my ($self, $container, $service_to_find) = @_;
    # look through all the current services
    return $container->get($service_to_find) if $container->hasService($service_to_find);
    # if we have sub-containers, ...
    if ($container->hasSubContainers()) {
        # then loop through all the sub-containers
        foreach my $sub_container ($container->getAllSubContainers()) {
            my $service = $self->_recursiveSearch($sub_container, $service_to_find);
            return $service if defined $service;
        }
    }
    return undef;
}

1;

__END__