# -------------------------------------------------------------------------------------
# MKDoc::System::MPH
# -------------------------------------------------------------------------------------
#
#       Author : Jean-Michel Hiver (jhiver@mkdoc.com).
#    Copyright : (c) MKDoc Holdings Ltd, 2001
# 
#      Unauthorized modification, use, reuse, distribution or redistribution
#      of this module is stricly forbidden.
#
#    Description:
#
#      A module to make global SCALAR variables mod_perl friendly by isolating them
#      depending on the $ENV{SERVER_NAME} variable, allowing them to be persistent
#      across connections.
#
# -------------------------------------------------------------------------------------
package MKDoc::System::MPH;
use MKDoc;
use Carp;
use strict;


##
# $class->TIESCALAR ($oid);
# -------------------------
#   Creates a new MKDoc::System::MPH object that will provide transparent
#   mod_perl friendly global SCALAR variables
##
sub TIESCALAR
{
    my $class = shift;
    $class = ref $class || $class;
    my $self = bless {} => $class;
    return $self;
}


##
# $self->FETCH;
# -------------
#   This method is invoked when the tied variable is being accessed.
#   It returns the right scalar depending on $ENV{SERVER_NAME}, providing
#   mod_perl isolation for global variables
##
sub FETCH
{
    my $self = shift;
    
    # we must return the right value depending on $server_name
    # if $ENV{SERVER_NAME} is not defined (i.e. executing the script
    # from the command line), we want to define a use a fake server
    # name and issue a warning.
    my $server_name;
    unless (defined $ENV{SERVER_NAME})
    {
	carp 'SERVER_NAME_UNDEFINED: $ENV{SERVER_NAME} should be defined';
	$server_name = 'DUMMY';
    }
    else
    {
	$server_name = lc ($ENV{SERVER_NAME});
    }
    
    return $self->{$server_name};
}


##
# $self->STORE ($thing);
# ----------------------
#   This method is invoked when the tied variable is being stored.
#   It sets the right scalar depending on $ENV{SERVER_NAME}, providing
#   mod_perl isolation for global variables
##
sub STORE
{
    my $self  = shift;
    my $value = shift;

    # we must set the right value depending on $server_name
    # if $ENV{SERVER_NAME} is not defined (i.e. executing the script
    # from the command line), we want to define a use a fake server
    # name and issue a warning.
    my $server_name;
    unless (defined $ENV{SERVER_NAME})
    {
	carp 'SERVER_NAME_UNDEFINED: $ENV{SERVER_NAME} should be defined';
	$server_name = 'DUMMY';
    }
    else
    {
	$server_name = lc ($ENV{SERVER_NAME});
    }

    $self->{$server_name} = $value;
}


1;

