Perl inheritance same instance -


i trying build small application base module 'apps' , shared instance module "shared" among modules "view" , "request" data , methods in "shared" module available other modules extends (view, request, apps) same instance, below code example.

app.cgi

#!/usr/bin/perl  use moose; use apps;  $app = apps->new;  msg(); # exported, works ok $app->msg(); # method works ok  $view = $app->view; $view->msg; # view class method, works ok  print $app->charset . "\n"; # shared.pm, prints utf8, default $app->charset("windows-1256"); # change utf8 windows-1256 in shared.pm print $app->charset . "\n"; # ok, prints windows-1256 print $view->charset . "\n"; # not ok, same default utf8  exit; 

apps.pm

package apps; use moose; extends qw(shared); sub init {     print "true is: " . true()."\n"; } 1; 

view.pm

package view; use moose; extends qw(shared); sub msg {     print "hello msg view\n"; } 1; 

request.pm

package request; use moose; extends qw(shared); sub msg {     print "hello msg request\n"; } 1; 

when run app.cgi output:

hello msg shared hello msg shared hello msg view utf8 windows-1256 utf8 

what expecting is:

hello msg shared hello msg shared hello msg view utf8 windows-1256 windows-1256 

so changes shared module not reflected or shared view , other modules. how make 1 instance of object shared shared among extending classes.

my goal make packages extend on shared package , package should share same instance data among extensions.

shared shouldn't base class objects inherit from. shared class should separate inheritance point of view.

instead, each class should have attribute (this might private 1 called obscure beginning underscore), point shared object shared class. when 1 object creates object (in example, $app object creates $view object) can assign new object pointer instance of shared class.

something this:

use v5.14;  package shared {     use moose;     has foo => (is => 'rw', default => 99);     has bar => (is => 'rw', default => 42); }  package app {     use moose;     has _common => (               => 'ro',         default  => sub { shared->new },         handles  => [qw/ foo bar /],     );     sub view {        $self = shift;        view->new(@_, _common => $self->_common);     } }  package view {     use moose;     has _common => (               => 'ro',         required => 1,         handles  => [qw/ foo bar /],     ); }  $app = app->new; $view = $app->view;  '$app->foo : ', $app->foo; '$view->foo : ', $view->foo;  # change value of $app->foo. # shared $view. $app->foo(66);  '$app->foo : ', $app->foo; '$view->foo : ', $view->foo; 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -