Beam::Wire - Lightweight Dependency Injection Container
version 1.026
# wire.yml
captain:
class: Person
args:
name: Malcolm Reynolds
rank: Captain
first_officer:
$class: Person
name: Zoë Alleyne Washburne
rank: Commander
# script.pl
use Beam::Wire;
my $wire = Beam::Wire->new( file => 'wire.yml' );
my $captain = $wire->get( 'captain' );
print $captain->name; # "Malcolm Reynolds"
Beam::Wire is a configuration module and a dependency injection container. In addition to complex data structures, Beam::Wire configures and creates plain old Perl objects.
A dependency injection (DI) container creates an inversion of control: Instead of manually creating all the dependent objects (also called "services") before creating the main object that we actually want, a DI container handles that for us: We describe the relationships between objects, and the objects get built as needed.
Dependency injection is sometimes called the opposite of garbage collection. Rather than ensure objects are destroyed in the right order, dependency injection makes sure objects are created in the right order.
Using Beam::Wire in your application brings great flexibility, allowing users to easily add their own code to customize how your project behaves.
For an introduction to the Beam::Wire service configuration format, see Beam::Wire::Help::Config.
The path of the file where services are configured (typically a YAML file). The file's contents should be a single hashref. The keys are service names, and the values are service configurations.
The directory path to use when searching for inner container files. Defaults to the directory which contains the file specified by the file attribute.
The raw configuration data. By default, this data is loaded by Config::Any using the file specified by the file attribute.
See Beam::Wire::Help::Config for details on what the configuration data structure looks like.
If you don't want to load a file, you can specify this attribute in the Beam::Wire constructor.
A hashref of cached services built from the configuration. If you want to inject a pre-built object for other services to depend on, add it here.
The character that begins a meta-property inside of a service's args
. This
includes $ref
, $path
, $method
, and etc...
The default value is $
. The empty string is allowed.
my $service = $wire->get( $name );
my $service = $wire->get( $name, %overrides )
The get method resolves and returns the service named $name
, creating
it, if necessary, with the create_service method.
%overrides
is an optional list of name-value pairs. If specified,
get() will create an new, anonymous service that extends the named
service with the given config overrides. For example:
# test.pl
use Beam::Wire;
my $wire = Beam::Wire->new(
config => {
foo => {
args => {
text => 'Hello, World!',
},
},
},
);
my $foo = $wire->get( 'foo', args => { text => 'Hello, Chicago!' } );
print $foo; # prints "Hello, Chicago!"
This allows you to create factories out of any service, overriding service configuration at run-time.
If $name
contains a slash (/
) character (e.g. foo/bar
), the left
side (foo
) will be used as the name of an inner container, and the
right side (bar
) is a service inside that container. For example,
these two lines are equivalent:
$bar = $wire->get( 'foo/bar' );
$bar = $wire->get( 'foo' )->get( 'bar' );
Inner containers can be nested as deeply as desired (foo/bar/baz/fuzz
).
$wire->set( $name => $service );
The set method configures and stores the specified $service
with the
specified $name
. Use this to add or replace built services.
Like the get() method, above, $name
can contain a slash (/
)
character to traverse through nested containers.
my $conf = $wire->get_config( $name );
Get the config with the given $name
. Like the get() method,
above, $name
can contain slash (/
) characters to traverse
through nested containers.
my $out_conf = $self->normalize_config( $in_conf );
Normalize the given $in_conf
into to hash that the create_service
method expects. This method allows a service to be
defined with prefixed meta-names ($class
instead of class
) and
the arguments specified without prefixes.
For example, these two services are identical.
foo:
class: Foo
args:
fizz: buzz
foo:
$class: Foo
fizz: buzz
The $in_conf
must be a hash, and must already pass an is_meta
check.
my $service = $wire->create_service( $name, %config );
Create the service with the given $name
and %config
. Config can
contain the following keys:
-
class
The class name of an object to create. Can be combined with
method
, andargs
. An object of any class can be created with Beam::Wire. -
args
The arguments to the constructor method. Used with
class
andmethod
. Can be a simple value, or a reference to an array or hash which will be dereferenced and passed in to the constructor as a list.If the
class
consumes the Beam::Service role, the service'sname
andcontainer
will be added to theargs
. -
method
The method to call to create the object. Only used with
class
. Defaults to"new"
.This can also be an array of hashes which describe a list of methods that will be called on the object. The first method should create the object, and each subsequent method can be used to modify the object. The hashes should contain a
method
key, which is a string containing the method to call, and optionallyargs
andreturn
keys. Theargs
key works like the top-levelargs
key, above. The optionalreturn
key can have the special value"chain"
, which will use the return value from the method as the value for the service (The tutorial shows examples of this).If an array is used, the top-level
args
key is not used. -
value
The value of this service. Can be a simple value, or a reference to an array or hash. This value will be simply returned by this method, and is mostly useful when using container files.
value
can not be used withclass
orextends
. -
ref
A reference to another service. This may be paired with
call
orpath
. -
config
The path to a configuration file, relative to the dir attribute. The file will be read with Config::Any, and the resulting data structure returned.
value
can not be used withclass
orextends
. -
extends
The name of a service to extend. The named service's configuration will be merged with this configuration (via the merge_config method).
This can be used in place of the
class
key if the extended configuration contains a class. -
with
Compose a role into the object's class before creating the object. This can be a single string, or an array reference of strings which are roles to combine.
This uses Moo::Role and the create_class_with_roles method, which should work with any class (as it uses the Role::Tiny module under the hood).
This can be used with the
class
key. -
on
Attach an event handler to a Beam::Emitter subclass. This is an array of hashes of event names and handlers. A handler is made from a service reference (
$ref
or an anonymous service), and a subroutine to call on that service ($sub
).For example:
emitter: class: My::Emitter on: - my_event: $ref: my_handler $sub: on_my_event
This can be used with the
class
key.
This method uses the parse_args method to parse the args
key,
resolving references as needed.
my %merged = $wire->merge_config( %config );
If %config
contains an extends
key, merge the extended config together
with this one, returning the merged service configuration. This works recursively,
so a service can extend a service that extends another service just fine.
When merging, hashes are combined, with the child configuration taking
precedence. The args
key is handled specially to allow a hash of
args to be merged. A single element array of args is merged too, if the
element is a hash.
The configuration returned is a safe copy and can be modified without effecting the original config.
my @args = $wire->parse_args( $for_name, $class, $args );
Parse the arguments ($args
) for the given service ($for_name
) with
the given class ($class
).
$args
can be an array reference, a hash reference, or a simple
scalar. The arguments will be searched for references using the
find_refs method, and then a list of arguments will be
returned, ready to pass to the object's constructor.
Nested containers are handled specially by this method: Their inner references are not resolved by the parent container. This ensures that references are always relative to the container they're in.
my @resolved = $wire->find_refs( $for_name, @args );
Go through the @args
and recursively resolve any references and
services found inside, returning the resolved result. References are
identified with the is_meta method.
If a reference contains a $ref
key, it will be resolved by the
resolve_ref method. Otherwise, the reference will be
treated as an anonymous service, and passed directly to the
create_service method.
This is used when creating a service to ensure all dependencies are created first.
my $is_meta = $wire->is_meta( $ref_hash, $root );
Returns true if the given hash reference describes some kind of Beam::Wire service. This is used to identify service configuration hashes inside of larger data structures.
A service hash reference must contain at least one key, and must either
contain a prefixed key that could create or reference an
object (one of class
, extends
, config
, value
, or ref
) or,
if the $root
flag exists, be made completely of unprefixed meta keys
(as returned by the get_meta_names method).
The $root
flag is used by the get method to allow unprefixed
meta keys in the top-level hash values.
my %meta_keys = $wire->get_meta_names;
Get all the possible service keys with the meta prefix already attached.
my @value = $wire->resolve_ref( $for_name, $ref_hash );
Resolves the given dependency from the configuration hash ($ref_hash
)
for the named service ($for_name
). Reference hashes contain the
following keys:
-
$ref
The name of a service in the container. Required.
-
$path
A data path to pick some data out of the reference. Useful with
value
andconfig
services.# container.yml bounties: value: malcolm: 50000 zoe: 35000 simon: 100000 captain: class: Person args: name: Malcolm Reynolds bounty: $ref: bounties $path: /malcolm
-
$call
Call a method on the referenced object and use the resulting value. This may be a string, which will be the method name to call, or a hash with
$method
and$args
, which are the method name to call and the arguments to that method, respectively.captain: class: Person args: name: Malcolm Reynolds location: $ref: beacon $call: get_location bounty: $ref: news $call: $method: get_bounty $args: name: mreynolds
my @fixed = $wire->fix_refs( $for_container_name, @args );
Similar to the find_refs method. This method searches
through the @args
and recursively fixes any reference paths to be
absolute. References are identified with the is_meta
method.
This is used by the get_config method to ensure that the configuration can be passed directly in to the create_service method.
my $wire = Beam::Wire->new( %attributes );
Create a new container.
If there is an error internal to Beam::Wire, an exception will be thrown. If there is an error with creating a service or calling a method, the exception thrown will be passed- through unaltered.
The base exception class
An exception creating a Beam::Wire object
An exception loading the configuration file.
An exception with service information inside
The requested service or configuration was not found.
The configuration is invalid:
- Both "value" and "class" or "extends" are defined. These are mutually-exclusive.
The container emits the following events.
This event is emitted when a new service is configured, but before it is instantiated or any classes loaded. This allows altering of the configuration before the service is built. Already-built services will not fire this event.
Event handlers get a Beam::Wire::Event::ConfigService object as their only argument.
This event will bubble up from child containers.
This event is emitted when a new service is built. Cached services will not fire this event.
Event handlers get a Beam::Wire::Event::BuildService object as their only argument.
This event will bubble up from child containers.
-
BEAM_WIRE_DEBUG
If set, print a bunch of internal debugging information to STDERR.
- Doug Bell preaction@cpan.org
- Al Newkirk anewkirk@ana.io
- Al Tom al-tom.ru@yandex.ru
- Ben Moon guiltydolphin@gmail.com
- Bruce Armstrong bruce@armstronganchor.net
- Diab Jerius djerius@cfa.harvard.edu
- Kent Fredric kentnl@cpan.org
- mauke lukasmai.403@gmail.com
- Mohammad S Anwar mohammad.anwar@yahoo.com
- mohawk2 mohawk2@users.noreply.github.com
- Sven Willenbuecher sven.willenbuecher@gmx.de
This software is copyright (c) 2018-2021 by Doug Bell.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.