Dear Monks,
I would like you to share your opinions on the matter of passing the reference to a common object between a library components.
Let's imagine that we have a complex library that consists of a bunch of classes. There is the Library::Logger class that is being used by other components (e.g. the initialization method of Library initializes an object of the Library::Logger class and then the Library-based object uses the Library::Logger-based object to call the logging methods.
There are many other sub-classes that needs to use the same object too: Library::Foo, Library::Bar, Library::Baz. Moreover, there are Library::Foo::Schmoo, Library::Bar::Schmar and Library::Baz::Schmaz sub-classes, there are dozens of classes. The question is: how to let them all have the reference to the logger that had been initialized once by the Library-based object?
I see the following ways to acheive it:
- When a Library-based object initializes the Library::Foo-based object, it passes the link to the logger to the newly-created object: $obj = Library::Foo->new(logger => $self->_get_logger);. So the Library::Foo-based object could get the logger as $logger = $self->_get_logger.
- When a Library-based object initializes the Library::Foo-based object, it passes the link to itself to the newly-created object: $obj = Library::Foo->new(papa => $self);. So the Library::Foo-based object could get the logger as $logger = $self->_get_papa->_get_logger. It breaks encapsulation, but it lets the Library::Foo-based object to get many other things from its "papa".
- Use a singleton (as MooseX::Singleton) or a global variable (as $Library::_logger) which seems to be even worse.
What do you think, which way seems to be better? What way would you propose? How do you solve this problem for yourself?
Many thanks in advance!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.