kropotkin wrote:
Hi Steven
Not quite. From the catalogue I want to see what is in the user's cart. As
they browse the catalogue they will see a flag next to each item if it is
in the basket; 'n already in your basket' sort of thing.
So from the class which produces catalogue pages I want to be able to obtain
information about the contents of this user's basket. You may say,
instantiate the basket class from the catalogue class and in many ways this
seems the simplest. I haven't done this because the both classes are part of
a framework. Basket does not have a constructor of its own but a method
which constructs it as part of the framework - I think what I probably need
is to create a new class which both these can use.
I don't think you need a delegator.
Store the 'global' cart (which is part of the user which is part of the
session) in the execution environment/scope.
The catalog code might say
GLOBALREQUEST->current_session->current_user->current_cart->is_in_cart('thisitem')
I have encountered this 'back call into execution context' a few times.
Generally to me this means you have a singleton pattern.
In a short concise code expression:
package Cart;
my $instance;
sub new { return $instance ||= bless {}, $self }
sub is_in_cart { ... }
package Catalog;
sub show_flag {
my $self = shift;
Cart->new->is_in_cart(shift);
}
The function new on Cart returns any already created instance if it
exists and creates a new one if not.
The package Catalog merely calls Cart->new when it wants a Cart, without
having to worry about whether or not there is an instance of it yet or
not (Cart class's problem) - since the same instance is returned on
every call to new, that makes the Cart a singleton. It can be accessed
from anywhere in the interpreter that has access to the Cart namespace
by a static call to Cart->new
This lets you do things like lazy-create a cart object only when needed,
and if there can't be a cart object for whatever reason you can use the
Nothing/Null pattern - return an object that, to its interface, looks
like a cart (same methods) but putting something into it is a noop and
getting its list of contents is always an empty set... thus avoiding
constantly checking to see if the object is not available in your code.
I'm babbling aren't I.
David