.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Bread::Board::Manual::Concepts 3pm" .TH Bread::Board::Manual::Concepts 3pm "2022-12-12" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Bread::Board::Manual::Concepts \- An overview of the concepts in Bread::Board .SH "VERSION" .IX Header "VERSION" version 0.37 .SH "INTRODUCTION" .IX Header "INTRODUCTION" This document attempts to convey the central concepts of Bread::Board and show how they work together to manage both object lifecycles and object dependencies. .PP In this document we use the raw \s-1OO\s0 syntax of Bread::Board, this is so that the concepts being illustrated are not clouded by syntactic sugar. We only introduce the \fIsugar\fR layer at the end, at which point we hope that it will become clear what is going on \*(L"under the hood\*(R" when you use it. .SH "CONCEPTS" .IX Header "CONCEPTS" .SS "What is Inversion of Control?" .IX Subsection "What is Inversion of Control?" Inversion of Control (or IoC) is the very simple idea of releasing control of some part of your application over to some other part of your application, be it your code or an outside framework. .PP IoC is a common paradigm in \s-1GUI\s0 frameworks, whereby you give up control of your application flow to the framework and install your code at callbacks hooks within the framework. For example, take a very simple command line interface; the application asks a question, the user responds, the application processes the answer and asks another question, and so on until it is done. Now consider the \s-1GUI\s0 approach for the same application; the application displays a screen and goes into an event loop, users actions are processed with event handlers and callback functions. The \s-1GUI\s0 framework has inverted the control of the application flow and relieved your code from having to deal with it. .PP IoC is also sometimes referred to as 'Dependency Injection' or the \&'Dependency Injection Principle', and many people confused the two. However IoC and dependency injection are not the same, in fact the concepts behind dependency injection are actually just an \&\fIexample of\fR IoC principles in action, in particular about your applications dependency relationships. IoC is also sometimes referred to as the Hollywood Principle because of the \fIdon't call us we'll call you\fR approach of things like callback functions and event handlers. .PP Howard Lewis Ship, the creator of the HiveMind IoC Framework, once referred to dependency injection as being the inverse of garbage collection. With garbage collection you hand over the details of the destruction of your objects to the garbage collector. With dependency injection you are handing over control of object creation, which also includes the satisfaction of your dependency relationships. .PP The following sections will explain the basis concepts around the Bread::Board and how it relates to the concept of IoC. .SS "Containers" .IX Subsection "Containers" The central part of just about any IoC framework is the container. A container's responsibilities are roughly to dispense services and to handle the resolution of said service's dependency relationships. .PP First we can start with a simple container for our services to live in. We give the container a name so that we can address it later on, think of this like a package namespace. .PP .Vb 1 \& my $c = Bread::Board::Container\->new( name => \*(AqApplication\*(Aq ); .Ve .PP Next we need to add a service to that container (we will explain services a little later on). .PP .Vb 6 \& $c\->add_service( \& Bread::Board::BlockInjection\->new( \& name => \*(Aqlogger\*(Aq, \& block => sub { Logger\->new() } \& ) \& ); .Ve .PP Now if we want an instance of our 'logger' service, we simply ask the container for it. .PP .Vb 1 \& my $logger_service = $c\->fetch(\*(Aqlogger\*(Aq); .Ve .PP And we then can ask the service to give us an instance of our Logger object. .PP .Vb 1 \& my $logger = $logger_service\->get; .Ve .PP Or if we want to make this even simpler we can use the \f(CW\*(C`resolve\*(C'\fR method of the container object. .PP .Vb 1 \& my $logger = $c\->resolve( service => \*(Aqlogger\*(Aq ); .Ve .PP The \f(CW\*(C`resolve\*(C'\fR method will look up the service asked for and return the instance, which is basically equivalent to the chained \f(CW\*(C`fetch\*(C'\fR and \f(CW\*(C`get\*(C'\fR calls above. .SS "Dependency Management" .IX Subsection "Dependency Management" Dependency management is also quite simple, and is easily shown with an example. But first lets create another component for our container, a database connection. .PP .Vb 6 \& $c\->add_service( \& Bread::Board::BlockInjection\->new( \& name => \*(Aqdb_conn\*(Aq, \& block => sub { DBI\->connect(\*(Aqdbi:mysql:test\*(Aq, \*(Aq\*(Aq, \*(Aq\*(Aq) } \& ) \& ); .Ve .PP Now lets add an authenticator to our container. The authenticator requires both a database connection and a logger instance in its constructor. We specify dependency relationships between services by providing a \s-1HASH\s0 of Bread::Board::Dependency objects which themselves have a path to the services they depend upon. In this case since all these services are in the same container, the service path is simply the name. .PP .Vb 10 \& $c\->add_service( \& Bread::Board::BlockInjection\->new( \& name => \*(Aqauthenticator\*(Aq, \& block => sub { \& my $service = shift; \& Authenticator\->new( \& db_conn => $service\->param(\*(Aqdb_conn\*(Aq), \& logger => $service\->param(\*(Aqlogger\*(Aq) \& ); \& }, \& dependencies => { \& db_conn => Bread::Board::Dependency\->new( \& service_path => \*(Aqdb_conn\*(Aq \& ), \& logger => Bread::Board::Dependency\->new( \& service_path => \*(Aqlogger\*(Aq \& ), \& } \& ) \& ); .Ve .PP As you can see, the first argument to our service subroutine is actually our service instance. Through this we can access the resolved dependencies and use them in our Authenticator object's constructor. .PP The above example is deceptively simple, but really powerful. What you don't see on the surface is that Bread::Board is completely managing initialization order for you. No longer to do you need to worry if your database is connected or your logger initialized and in what order you need to do that initialization, Bread::Board handles that all for you, including circular dependencies. This may not seem terribly interesting in such a small example, but the larger an application grows, the more sensitive it becomes to these kinds of initialization order issues. .SS "Lifecycle Management" .IX Subsection "Lifecycle Management" The default lifecycle for Bread::Board::Service components is a \&'prototype' lifecycle, which means each time we ask for say, the logger, we will get a new instance back. There is also another option for lifecycle management that we call 'Singleton'. Here is an example of how we would use the 'Singleton' lifecycle to ensure that you always get back the same logger instance. .PP .Vb 7 \& $c\->add_service( \& Bread::Board::BlockInjection\->new( \& lifecycle => \*(AqSingleton\*(Aq, \& name => \*(Aqlogger\*(Aq, \& block => sub { Logger\->new() } \& ) \& ); .Ve .PP Now each time we request a new logger component from our container we will get the exact same instance. Being able to change between the different lifecycles by simply changing one service parameter can come in very handy as you application grows. Extending this idea, it is possible to see how you could create your own custom service objects to manage your specific lifecycle needs, such as a pool of database connections. .SS "Services" .IX Subsection "Services" Up until now, we have shown the default way of creating a service by using the Bread::Board::BlockInjection and an anonymous subroutine. But this is not the only way to go about this. Those who have encountered IoC in the Java world may be familiar with the idea that there are 3 'types' of IoC/Dependency Injection; Constructor Injection, Setter Injection, and Interface Injection. In Bread::Board we support both Constructor and Setter injection, it is the authors opinion though that Interface injection was not only too complex, but highly java specific and the concept did not adapt itself well to perl. .IP "Block Injection" 4 .IX Item "Block Injection" While not in the 'official' 3 types (mostly because it's not possible in Java), but found in a few Ruby IoC frameworks, BlockInjection is by far the most versatile type. It simply requires a subroutine and a name and you do all the rest of it yourself. .Sp .Vb 10 \& $c\->add_service( \& Bread::Board::BlockInjection\->new( \& name => \*(Aqlogger\*(Aq, \& class => \*(AqComplexLogger\*(Aq, \& block => sub { \& my $s = shift; \& my $l = ComplexLogger\->new( \& file => $s\->param(\*(Aqlog_file\*(Aq) \& ); \& $l\->init_with_timezone( $s\->param(\*(Aqtimezone\*(Aq) ); \& $l\->log_timestamp; \& $l; \& }, \& dependencies => { \& log_file => Bread::Board::Dependency\->new( \& service_path => \*(Aqlog_file\*(Aq \& ), \& timezone => Bread::Board::Dependency\->new( \& service_path => \*(Aqtimezone\*(Aq \& ), \& } \& ) \& ); .Ve .Sp BlockInjection comes in really handy when your object requires more then just constructor parameters and needs some more complex initialization code. As long as your subroutine block returns an object, everything else is fair game. Also note the optional 'class' parameter, which when supplied will perform a basic type check on the result of the subroutine block. .IP "Constructor Injection" 4 .IX Item "Constructor Injection" Bread::Board also supports Constructor Injection. With constructor injection, the service calls the class's constructor and feeds it the dependencies you specify. This promotes what is called a \&\*(L"Good Citizen\*(R" object, or an object who is completely initialized upon construction. .Sp .Vb 10 \& $c\->add_service( \& Bread::Board::ConstructorInjection\->new( \& name => \*(Aqauthenticator\*(Aq, \& class => \*(AqAuthenticator\*(Aq, \& dependencies => { \& db_conn => Bread::Board::Dependency\->new( \& service_path => \*(Aqdb_conn\*(Aq \& ), \& logger => Bread::Board::Dependency\->new( \& service_path => \*(Aqlogger\*(Aq \& ), \& } \& ) \& ); .Ve .Sp Since Bread::Board is built both with Moose and for use with Moose objects, it makes the assumption here that the constructor takes named arguments. Here is our earlier authenticator service rewritten to use constructor injection. This is by far the simplest injection type as it requires little more then a class name and a \s-1HASH\s0 of dependencies. .IP "Setter Injection" 4 .IX Item "Setter Injection" Bread::Board also supports Setter Injection. The idea behind setter injection is that for each component dependency a corresponding setter method must exist. This style has been popularized by the Spring java framework. I will be honest, I don't find this type of injection as useful as block or constructor, but it can come in handy if your object prefers you to call setters to initialize it. Here is a fairly contrived example using the \s-1JSON\s0 module. .Sp .Vb 10 \& $c\->add_service( \& Bread::Board::SetterInjection\->new( \& name => \*(Aqjson\*(Aq, \& class => \*(AqJSON\*(Aq, \& dependencies => { \& utf8 => Bread::Board::Literal\->new( \& name => \*(Aqtrue\*(Aq, \& value => 1 \& ) \& pretty => Bread::Board::Literal\->new( \& name => \*(Aqtrue\*(Aq, \& value => 1 \& ) \& } \& ) \& ); .Ve .Sp Setter injection actually creates the object without passing any arguments to the constructor, then loops through the keys in the dependency \s-1HASH\s0 and treats each key as a method name, and each value as that method's argument. In this case, the above is the equivalent of doing: .Sp .Vb 3 \& my $json = JSON\->new; \& $json\->utf8(1); \& $json\->pretty(1); .Ve .Sp You might have been wondering about the fact we didn't specify Bread::Board::Dependency objects in our dependency \s-1HASH,\s0 but instead supplied Bread::Board::Literal instances. Bread::Board::Literal is just another Service type that simply holds a literal value, or a constant. When dependencies are specified like this, Bread::Board internally converts them into Bread::Board::Dependency whose service is already resolved to that service. .SS "Hierarchical Containers" .IX Subsection "Hierarchical Containers" Up until now, we have seen basic containers which only have a single level of components. As your application grows larger it may become useful to have a more hierarchical approach to your containers. Bread::Board::Container supports this behavior through its many sub-container methods. Here is an example of how we might re-arrange the previous examples using sub-containers. .PP .Vb 1 \& my $app_c = Bread::Board::Container\->new( name => \*(Aqapp\*(Aq ); \& \& my $db_c = Bread::Board::Container\->new( name => \*(Aqdatabase\*(Aq ); \& $db_c\->add_service( \& Bread::Board::BlockInjection\->new( \& name => \*(Aqdb_conn\*(Aq \& block => sub { \& my $s = shift; \& return DBI\->connect( \& $s\->param(\*(Aqdsn\*(Aq), \& $s\->param(\*(Aqusername\*(Aq), \& $s\->param(\*(Aqpassword\*(Aq) \& ); \& }, \& dependencies => { \& dsn => Bread::Board::Literal\->new( \& name => \*(Aqdsn\*(Aq, \& value => \*(Aqdbi:mysql:test\*(Aq \& ), \& username => Bread::Board::Literal\->new( \& name => \*(Aqusername\*(Aq, \& value => \*(Aquser\*(Aq \& ), \& password => Bread::Board::Literal\->new( \& name => \*(Aqpassword\*(Aq, \& value => \*(Aq****\*(Aq \& ), \& } \& ) \& ); \& \& $app_c\->add_sub_container( $db_c ); \& \& my $log_c = Bread::Board::Container\->new( name => \*(Aqlogging\*(Aq ); \& $log_c\->add_service( \& Bread::Board::Literal\->new( \& name => \*(Aqlog_file\*(Aq, \& value => \*(Aq/var/log/app.log\*(Aq \& ) \& ); \& $log_c\->add_service( \& Bread::Board::ConstructorInjection\->new( \& name => \*(Aqlogger\*(Aq, \& class => \*(AqLogger\*(Aq, \& dependencies => { \& log_file => Bread::Board::Dependency\->new( \& service_path => \*(Aqlog_file\*(Aq \& ) \& } \& ) \& ); \& \& $app_c\->add_sub_container( $log_c ); \& \& my $sec_c = Bread::Board::Container\->new( name => \*(Aqsecurity\*(Aq ); \& $sec_c\->add_service( \& Bread::Board::ConstructorInjection\->new( \& name => \*(Aqauthenticator\*(Aq, \& class => \*(AqAuthenticator\*(Aq, \& dependencies => { \& db_conn => Bread::Board::Dependency\->new( \& service_path => \*(Aq../database/db_conn\*(Aq \& ), \& logger => Bread::Board::Dependency\->new( \& service_path => \*(Aq../logging/logger\*(Aq \& ), \& } \& ) \& ); \& \& $app_c\->add_sub_container( $sec_c ); \& \& $app_c\->add_service( \& Bread::Board::ConstructorInjection\->new( \& name => \*(Aqapp\*(Aq, \& class => \*(AqApplication\*(Aq, \& dependencies => { \& auth => Bread::Board::Dependency\->new( \& service_path => \*(Aq/security/authenticator\*(Aq \& ), \& db_conn => Bread::Board::Dependency\->new( \& service_path => \*(Aq/database/db_conn\*(Aq \& ), \& logger => Bread::Board::Dependency\->new( \& service_path => \*(Aq/logging/logger\*(Aq \& ), \& } \& ) \& ); .Ve .PP So, as an example that can be seen above, hierarchical containers can be used as a form of namespacing to organize your Bread::Board configuration better. As it is shown with the 'authenticator' service, it is possible to address services outside of your container using path notation. In this case the 'authenticator' service makes the assumption that its parent container has both a \&'database' and a 'logging' sub-container and they contain a \&'db_conn' and 'logger' service respectively. And as is shown in the 'app' service, it is also possible to address services using an absolute path notation. .SS "Sugar Layer" .IX Subsection "Sugar Layer" So, up until now we have been creating all our Bread::Board objects by hand. As you can tell, this is both verbose and tedious. To make your life easier, Bread::Board provides a simple \fIsugar\fR layer over these objects. Here is the equivalent of the above Bread::Board configuration using the sugar layer. .PP .Vb 1 \& my $c = container \*(Aqapp\*(Aq => as { \& \& container \*(Aqdatabase\*(Aq => as { \& service \*(Aqdb_conn\*(Aq => ( \& block => sub { \& my $s = shift; \& return DBI\->connect( \& $s\->param(\*(Aqdsn\*(Aq), \& $s\->param(\*(Aqusername\*(Aq), \& $s\->param(\*(Aqpassword\*(Aq) \& ); \& }, \& dependencies => { \& dsn => ( service \*(Aqdsn\*(Aq => \*(Aqdbi:mysql:test\*(Aq ), \& username => ( service \*(Aqusername\*(Aq => \*(Aquser\*(Aq ), \& password => ( service \*(Aqpassword\*(Aq => \*(Aq****\*(Aq ), \& } \& ) \& }; \& \& container \*(Aqlogging\*(Aq => as { \& service \*(Aqlog_file\*(Aq => \*(Aq/var/log/app.log\*(Aq; \& service \*(Aqlogger\*(Aq => ( \& class => \*(AqLogger\*(Aq, \& dependencies => { \& log_file => depends_on(\*(Aqlog_file\*(Aq), \& } \& ) \& }; \& \& container \*(Aqsecurity\*(Aq => as { \& service \*(Aqauthenticator\*(Aq => ( \& class => \*(AqAuthenticator\*(Aq, \& dependencies => { \& db_conn => depends_on(\*(Aq../database/db_conn\*(Aq), \& logger => depends_on(\*(Aq../logging/logger\*(Aq), \& } \& ) \& }; \& \& service \*(Aqapp\*(Aq => ( \& class => \*(AqApplication\*(Aq, \& dependencies => { \& auth => depends_on(\*(Aq/security/authenticator\*(Aq), \& db_conn => depends_on(\*(Aq/database/db_conn\*(Aq), \& logger => depends_on(\*(Aq/logging/logger\*(Aq), \& } \& ) \& }; .Ve .PP As you can see this not only makes the code shorter, but more declarative and easier to read. .SH "SEE ALSO" .IX Header "SEE ALSO" This article is based on an article I wrote for The Perl Journal about my earlier \s-1IOC\s0 module. That article can be found online at . .SH "AUTHOR" .IX Header "AUTHOR" Stevan Little .SH "BUGS" .IX Header "BUGS" Please report any bugs or feature requests on the bugtracker website https://github.com/stevan/BreadBoard/issues .PP When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2019, 2017, 2016, 2015, 2014, 2013, 2011, 2009 by Infinity Interactive. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.