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
In reply to Re: Passing the logger's object (updated)
by haukex
in thread Passing the logger's object
by v_melnik
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |