in reply to Passing the logger's object
Hi v_melnik,
Globals have a bad reputation because they are so commonly misused. But that doesn't make all globally accessible values bad: Will you ever have a need for more than one logger object in your entire application? And you can still use an OO approach and encapsulate the retrieval of the globally accessible value in a method, allowing for you to later change how loggers are retrieved (admittedly, if you make it a class method, that limits it a bit, but luckily in Perl class and instance methods are very similar). Here are just a few examples of the many possibilities:
use warnings; use strict; use feature 'state'; package Library; sub new { bless {}, shift } sub logger { # Just an example; # could be class or instance method / property, # could hand out different logger objects. state $logger = Library::Logger->new; return $logger; } package Library::Logger; sub new { bless {}, shift } sub log { shift; print "[".gmtime." UTC] @_\n" } package Library::Foo; sub new { bless {}, shift } sub foo { Library->logger->log("access via class method works") } package Library::Bar; use parent -norequire, 'Library'; sub bar { shift->logger->log("inheritance works") } package Library::Quz; sub new { my $class = shift; bless {@_}, $class } sub library { shift->{library} } sub quz { shift->library->logger->log("access via property works") } package main; Library::Foo->new->foo; Library::Bar->new->bar; my $lib = Library->new; $lib->logger->log("access via instance method works"); Library::Quz->new(library=>$lib)->quz;
Update: Added Library::Quz class and updated example code accordingly; added some comments.
Hope this helps,
-- Hauke D
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Passing the logger's object (updated)
by v_melnik (Scribe) on Nov 13, 2016 at 20:05 UTC | |
by stevieb (Canon) on Nov 13, 2016 at 20:59 UTC | |
by haukex (Archbishop) on Nov 14, 2016 at 10:16 UTC |