How to implement a full Observer pattern in PHP - php

An Observer Design Pattern is the solution to loosely coupling objects so they can work together. In PHP you can easily implement this using just two classes.
Basically, you have a subject which is able to notify and update a list of observers of its state changes.
The problem I'm trying to solve is to know how to handler alerting the observers about different states of the object they are watching.
For example, lets say we have a file upload class to which we attach a logging class, websockets class, and a image resize class. Each of these classes that are watching want to know about different events in the upload process.
This file upload class might have three places where it needs to notify the classes listening that something has happend.
Error With Upload (alert logging class)
Upload success (alert websockets class)
Upload success and is image file (alert image resize class)
This is a very basic example, but how do you handle multiple events that different observers may need to know about? Calling notifyObservers() alone wouldn't be enough since each observer needs to know what it is being notified about.
One thought is that I could state with the call what type of event is being observed:
$this->notifyObservers('upload.error', this);
However, that would mean I would have to add custom switching to the observers themselves to know how to handle different events.
function observe($type, $object)
{
if($type === 'upload.error') $this->dosomething();
elseif($type === 'something.else') $this->otherthing();
...etc...
}
I find that very ugly as it starts to couple the observers back to the class they are observing.
Then again, if I just notify Observers without passing any information about what event just happens - they have to guess themselves what is going on which means more if() checks.

The observers aren't actually coupled to the class they are observing. The connection between the observer's handler and the observed object is made using literal string values (e.g. `upload.error'), which means that:
If you want to observe a specific object, you have to know from beforehand the names of the events it will publishing; this is the "coupling" that you don't like.
On the other hand, if you are interested in a specific event only, you can observe any type of object for that event without having any knowledge about that object.
Item 2 above is a benefit that you care about, but what to do about item 1?
If you think about it, there needs to be some way to differentiate between callbacks to the same observer if they represent different events taking place. These "identifiers", no matter what form they take, need to be packaged either into the observed object or be a part of the observer library code.
In the first instance (inside observed object) you would probably need a way for observers to query "do you ever publish event X?" before starting to observe a target for that event. The target can answer this question just fine. This leaves a bitter taste of coupling, but if you want any object to observe any other, and you have no idea what you will be observing beforehand, I don't think you can do any better.
In the second approach, you would have a number of well-known events defined (as const inside a class?) in your library. Presumably such a list of events can be made because the library tackles a concrete application domain, and that domain offers obvious choices for the events. Then, classes both internal to your library (which would end up being observed) and external to it (the observers which plug into the framework) would use these identifiers to differentiate between events. Many callback-based APIs (such as Win32) use an approach practically identical to this.

Related

Mixing together DDD with Event Sourcing

I can't get my head around concept of mixing together DDD with ES. I consider events as being part of domain side. Given that there is no problem with publishing them from repository to outside world and keeping models pure and simple. But aside from that there must be possibility of replaying them back on particular aggregate. This is where my problem occurs. I would like to keep my domain models pure and simple objects that remain lib/framework agnostic.
To apply past events on aggregate the aggregate must be aware of being part of ES structure (wherefore it would not remain pure domain object). As main job of aggregate is to enfroce some bussines invariants that may evolve over time it is impossible to apply old events using aggregate API. For instance, there is aggregate Post with child entities Comments. Today Post allows 10 Comments to be added, and method addCommnet() guards that rule. But it is not used to be that way all time. One year ago user was allowed to add up to 20 Comments. So appying past events may not meet current rules.
Broadway (popular PHP CQRS library) works around the problem by applying events without any prevalidation. Method addCommnet() just checks it against our invariants and then processes appling events. Applyinig event itself does not do any further checking. That is greaat but I perceive that as high level of integration in my domain models. Does really my domain model need to know anything about infastructure (which is ES style of saving data)?
EDIT:
To state the problem with the simplest words possible: is there any opportunity to get rid of all those applyXXX() methods from aggregate?
EDIT2:
I have written (bit hacky) PoC of this idea with PHP - github
Disclaimer: I'm a CQRS framework guy.
Broadway (popular PHP CQRS library) works around the problem by applying events without any prevalidation. 
That's the way every CQRS Aggregate works, events are not checked because they express facts that already happened in the past. This means that applying an event doesn't throw exceptions, ever.
To apply past events on aggregate the aggregate must be aware of being part of ES structure (wherefore it would not remain pure domain object)
No, it doesn't. It must be aware of its past events. That is good.
Today Post allows 10 Comments to be added, and method addCommnet() guards that rule. But it is not used to be that way all time. One year ago user was allowed to add up to 20 Comments. So appying past events may not meet current rules.
What keeps you aggregate from ignoring that event or to interpret differently than 1 year ago?!
This particular case should make you think about the power of CQRS: writes have a different logic than reads. You apply the events on the aggregate in order to validate the future commands that arrive at it (the write/command side). Displaying those 20 events is handled by other logic (the read/query side).
This is where my problem occurs. I would like to keep my domain models pure and simple objects that remain lib/framework agnostic.
CQRS make possible to keep your aggregates pure (no side effects), no dependency to any library and simple. I do this using the style presented by cqrs.nu, by yielding events. This means that aggregate command handlers methods are in fact generators.
The read models can also very very simple, plain PHP immutable objects. Only the read model updater has dependency to persistence, but that can be inversed using an interface.
I can't get my head around concept of mixing together DDD with CQRS.
From the sound of things, you can't quite get your head around the mix of DDD and event sourcing. CQRS and Event Sourcing are separate ideas (that happen to go together well).
Today Post allows 10 Comments to be added, and method addCommnet() guards that rule. But it is not used to be that way all time. One year ago user was allowed to add up to 20 Comments. So appying past events may not meet current rules.
That's absolutely true. Notice, however, that it is also true that if you had a non event sourced post with 15 comments, and you try to make a "rule" now that only 10 comments are allowed, you still have a problem.
My answer to this puzzle (in both styles) is that you need a slightly different understanding of the responsibilities involved.
The responsibility of the domain model is behavior; it describes which states are reachable from the current state. The domain model shouldn't restrict you from being in a bad state, it should prevent good states from becoming bad states.
In version one, we might say that the state of a Post includes a TwentyList of Comments, where a TwentyList is (surprise) a container that can hold up to 20 comment identifiers.
In version two, where we want to maintain a limit of 10 comments, we don't change the TwentyList to a TenList, because that gives us backward compatibility headaches. Instead, we change the domain rule to say "no comments may be added to a post with 10 or more comments". The data schema is unchanged, and the undesirable states are still representable, but the allowed state transitions are greatly restricted.
Ironically enough, a good book to read to get more insights is Greg Young's Versioning in an Event Sourced System. The lesson, at a high level, is that event versioning is just message versioning, and state is just a message that a previous model left behind for the current model.
Value types aren't about rule constraints, they are about semantic constraints.
Keep in mind that the timelines are very different; behaviors are about the now and next, but states are about the past. States are supposed to endure much longer than behaviors (with the corresponding investment in design capital that implies).
Does really my domain model need to know anything about infrastructure (which is ES style of saving data)?
No, the domain model should not need to know about infrastructure.
But events aren't infrastructure -- they are state. A journal of AddComment and RemoveComment events is state just like a list of Comment entries is state.
The most general form of "behavior" is a function that takes current state as its input and emits events as its output
List<Event> act(State currentState);
as we can always at an outer layer, take the events (which are a non destructive representation of the state, and build the state from them.
State act(State currentState) {
List<Event> changes = act(currentState)
State nextState = currentState.apply(changes)
return nextState
}
List<Event> act(List<Event> history) {
State initialState = new State();
State currentState = initialState.apply(changes)
return act(currentState)
}
State act(List<Event> history) {
// Writing this out long hand to drive home the point
// we could of course call act: List<Event> -> State
// to avoid duplication.
List<Event> changes = act(history)
State initialState = new State()
State currentState = initialState.apply(history)
State nextState = currentState.apply(changes)
return nextState;
}
The point being that you can implement the behavior in the most general case, add a few adapters, and then let the plumbing choose which implementation is most appropriate.
Again, separation of responsibilities is your guiding star: state that manages what is, behavior that manages what changes are allowed, and plumbing/infrastructure are all distinct concerns.
In the simplest terms: I'm looking for opportunity to get rid of many applyXXX() (or similar in languages with overloading methods) methods from my aggregate
applyXXX is just a function, that accepts a State and an Event as arguments and returns a new State. You can use any spelling and scoping you want for it.
My answer is very short. Indeed, it is event-sourcing that you struggle with, not CQRS.
If handling of some event changes over time, you have two scenarios really:
You are fixing a bug and your handler should really behave differently. In this case you just proceed with the change.
You got some new intent. You actually have a new handling. This means that in fact this is a different event. In this case you have a new event and new handler.
These scenarios have no relation to programming languages and frameworks. Event-sourcing in general is much more about the business that about any tech.
I would second to Greg's book recommendation.
I think that your problem is that you want to validate events when they are applied, but apply and validation are two different stages of aggregate action. When you are adding comment by method addComment(event), there is your logic to validate and this method is throwing event, when you reply event this logic is not checking again. Past event can not be changed, and if your aggregate throws exception with reply event something is wrong with your aggregate. That's how I understand your problem.

Structure for a Actions Engine

I am working on a project that requires a basic Actions engine so that certain functions can be bound to certain events, and other functions can call certain events. Just like the Wordpress Hooks system (except without the filters).
I know I could copy the Wordpress one, but I want to get some clarification on a thought. This project will grow quite large, and at the moment, will contain around 1200 events and over 2000 callbacks to be bound to those events, and those figures will only grow. So, would it be best to (in terms of performance):
A)
Have a single class with static functions/a set of functions on their own which will act as the repository for all these bindings, and is the sole interface for this functionality
B)
To build a class containing the functions, but when applications want to Bind a function, or Call an event, they need to access (probably contained within a global registry, havent decided yet) the instantiated Event object that contains specific Events, as per which instance is used.
So, my question is, would B be more performant (by dividing up the events into smaller groups), or would A be sufficient in this case?
Well, there is more than one thing to consider in this two strategies.
A) For what I have understood will have best performance over B if you use some array structure in B to find the events, but will be over more complex to maintain and scale, since you gonna need to write everithing in a class that gonna be huge
B) may become less performatic but easier to use and scale as a event engine.
I believe the best choice to implement would be to use B as a kind of Event Dispatcher Pattern. Look this gist https://gist.github.com/nunomazer/8472389, the code is from this article http://www.cainsvault.com/design-pattern-php-event-dispatcher/. It implements a simple event manager based on Observer Pattern.
But if I were use an event manager, probably I would consider one from a framework, like Symfony Event Dispatcher component that is ready and allow you to use it as a library in your project.

How do I architect my classes for easier unit testing?

I'll admit, I haven't unit tested much... but I'd like to. With that being said, I have a very complex registration process that I'd like to optimize for easier unit testing. I'm looking for a way to structure my classes so that I can test them more easily in the future. All of this logic is contained within an MVC framework, so you can assume the controller is the root where everything gets instantiated from.
To simplify, what I'm essentially asking is how to setup a system where you can manage any number of third party modules with CRUD updates. These third party modules are all RESTful API driven and response data is stored in local copies. Something like the deletion of a user account would need to trigger the deletion of all associated modules (which I refer to as providers). These providers may have a dependency on another provider, so the order of deletions/creations is important. I'm interested in which design patterns I should specifically be using to support my application.
Registration spans several classes and stores data in several db tables. Here's the order of the different providers and methods (they aren't statics, just written that way for brevity):
Provider::create('external::create-user') initiates registration at a particular step of a particular provider. The double colon syntax in the first param indicates the class should trigger creation on providerClass::providerMethod. I had made a general assumption that Provider would be an interface with the methods create(), update(), delete() that all other providers would implement it. How this gets instantiated is likely something you need to help me with.
$user = Provider_External::createUser() creates a user on an external API, returns success, and user gets stored in my database.
$customer = Provider_Gapps_Customer::create($user) creates a customer on a third party API, returns success, and stores locally.
$subscription = Provider_Gapps_Subscription::create($customer) creates a subscription associated to the previously created customer on the third party API, returns success, and stores locally.
Provider_Gapps_Verification::get($customer, $subscription) retrieves a row from an external API. This information gets stored locally. Another call is made which I'm skipping to keep things concise.
Provider_Gapps_Verification::verify($customer, $subscription) performs an external API verification process. The result of which gets stored locally.
This is a really dumbed down sample as the actual code relies upon at least 6 external API calls and over 10 local database rows created during registration. It doesn't make sense to use dependency injection at the constructor level because I might need to instantiate 6 classes in the controller without knowing if I even need them all. What I'm looking to accomplish would be something like Provider::create('external') where I simply specify the starting step to kick off registration.
The Crux of the Problem
So as you can see, this is just one sample of a registration process. I'm building a system where I could have several hundred service providers (external API modules) that I need to sign up for, update, delete, etc. Each of these providers gets related back to a user account.
I would like to build this system in a manner where I can specify an order of operations (steps) when triggering the creation of a new provider. Put another way, allow me to specify which provider/method combination gets triggered next in the chain of events since creation can span so many steps. Currently, I have this chain of events occurring via the subject/observer pattern. I'm looking to potentially move this code to a database table, provider_steps, where I list each step as well as it's following success_step and failure_step (for rollbacks and deletes). The table would look as follows:
# the id of the parent provider row
provider_id int(11) unsigned primary key,
# the short, slug name of the step for using in codebase
step_name varchar(60),
# the name of the method correlating to the step
method_name varchar(120),
# the steps that get triggered on success of this step
# can be comma delimited; multiple steps could be triggered in parallel
triggers_success varchar(255),
# the steps that get triggered on failure of this step
# can be comma delimited; multiple steps could be triggered in parallel
triggers_failure varchar(255),
created_at datetime,
updated_at datetime,
index ('provider_id', 'step_name')
There's so many decisions to make here... I know I should favor composition over inheritance and create some interfaces. I also know I'm likely going to need factories. Lastly, I have a lot of domain model shit going on here... so I likely need business domain classes. I'm just not sure how to mesh them all together without creating an utter mess in my pursuit of the holy grail.
Also, where would be the best place for the db queries to take place?
I have a model for each database table already, but I'm interested in knowing where and how to instantiate the particular model methods.
Things I've Been Reading...
Design Patterns
The Strategy Pattern
Composition over Inheritance
The Factory method pattern
The Abstract factory pattern
The Builder pattern
The Chain-of-responsibility pattern
You're already working with the pub/sub pattern, which seems appropriate. Given nothing but your comments above, I'd be considering an ordered list as a priority mechanism.
But it still doesn't smell right that each subscriber is concerned with the order of operations of its dependents for triggering success/failure. Dependencies usually seem like they belong in a tree, not a list. If you stored them in a tree (using the composite pattern) then the built-in recursion would be able to clean up each dependency by cleaning up its dependents first. That way you're no longer worried about prioritizing in which order the cleanup happens - the tree handles that automatically.
And you can use a tree for storing pub/sub subscribers almost as easily as you can use a list.
Using a test-driven development approach could get you what you need, and would ensure your entire application is not only fully testable, but completely covered by tests that prove it does what you want. I'd start by describing exactly what you need to do to meet one single requirement.
One thing you know you want to do is add a provider, so a TestAddProvider() test seems appropriate. Note that it should be pretty simple at this point, and have nothing to do with a composite pattern. Once that's working, you know that a provider has a dependent. Create a TestAddProviderWithDependent() test, and see how that goes. Again, it shouldn't be complex. Next, you'd likely want to TestAddProviderWithTwoDependents(), and that's where the list would get implemented. Once that's working, you know you want the Provider to also be a Dependent, so a new test would prove the inheritance model worked. From there, you'd add enough tests to convince yourself that various combinations of adding providers and dependents worked, and tests for exception conditions, etc. Just from the tests and requirements, you'd quickly arrive at a composite pattern that meets your needs. At this point I'd actually crack open my copy of GoF to ensure I understood the consequences of choosing the composite pattern, and to make sure I didn't add an inappropriate wart.
Another known requirement is to delete providers, so create a TestDeleteProvider() test, and implement the DeleteProvider() method. You won't be far away from having the provider delete its dependents, too, so the next step might be creating a TestDeleteProviderWithADependent() test. The recursion of the composite pattern should be evident at this point, and you should only need a few more tests to convince yourself that deeply nested providers, empty leafs, wide nodes, etc., all will properly clean themselves up.
I would assume that there's a requirement for your providers to actually provide their services. Time to test calling the providers (using mock providers for testing), and adding tests that ensure they can find their dependencies. Again, the recursion of the composite pattern should help build the list of dependencies or whatever you need to call the correct providers correctly.
You might find that providers have to be called in a specific order. At this point you might need to add prioritization to the lists at each node within the composite tree. Or maybe you have to build an entirely different structure (such as a linked list) to call them in the right order. Use the tests and approach it slowly. You might still have people concerned that you delete dependents in a particular externally prescribed order. At this point you can use your tests to prove to the doubters that you will always delete them safely, even if not in the order they were thinking.
If you've been doing it right, all your previous tests should continue to pass.
Then come the tricky questions. What if you have two providers that share a common dependency? If you delete one provider, should it delete all of its dependencies even though a different provider needs one of them? Add a test, and implement your rule. I figure I'd handle it through reference counting, but maybe you want a copy of the provider for the second instance, so you never have to worry about sharing children, and you keep things simpler that way. Or maybe it's never a problem in your domain. Another tricky question is if your providers can have circular dependencies. How do you ensure you don't end up in a self-referential loop? Write tests and figure it out.
After you've got this whole structure figured out, only then would you start thinking about the data you would use to describe this hierarchy.
That's the approach I'd consider. It may not be right for you, but that's for you to decide.
Unit Testing
With unit testing, we only want to test the code that makes up the individual unit of source code, typically a class method or function in PHP (Unit Testing Overview). Which indicates that we don't want to actually test the external API in Unit Testing, we only want to test the code we are writing locally. If you do want to test entire workflows, you are likely wanting to perform integration testing (Integration Testing Overview), which is a different beast.
As you specifically asked about designing for Unit Testing, lets assume you actually mean Unit Testing as opposed to Integration Testing and submit that there are two reasonable ways to go about designing your Provider classes.
Stub Out
The practice of replacing an object with a test double that (optionally) returns configured return values is refered to as stubbing. You can use a stub to "replace a real component on which the SUT depends so that the test has a control point for the indirect inputs of the SUT. This allows the test to force the SUT down paths it might not otherwise execute". Reference & Examples
Mock Objects
The practice of replacing an object with a test double that verifies expectations, for instance asserting that a method has been called, is referred to as mocking.
You can use a mock object "as an observation point that is used to verify the indirect outputs of the SUT as it is exercised. Typically, the mock object also includes the functionality of a test stub in that it must return values to the SUT if it hasn't already failed the tests but the emphasis is on the verification of the indirect outputs. Therefore, a mock object is lot more than just a test stub plus assertions; it is used a fundamentally different way".
Reference & Examples
Our Advice
Design your class to both all both Stubbing and Mocking. The PHP Unit Manual has an excellent example of Stubbing and Mocking Web Service. While this doesn't help you out of the box, it demonstrates how you would go about implementing the same for the Restful API you are consuming.
Where is the best place for the db queries to take place?
We suggest you use an ORM and not solve this yourself. You can easily Google PHP ORM's and make your own decision based off your own needs; our advice is to use Doctrine because we use Doctrine and it suits our needs well and over the past few years, we have come to appreciate how well the Doctrine developers know the domain, simply put, they do it better than we could do it ourselves so we are happy to let them do it for us.
If you don't really grasp why you should use an ORM, see Why should you use an ORM? and then Google the same question. If you still feel like you can roll your own ORM or otherwise handle the Database Access yourself better than the guys dedicated to it, we would expect you to already know the answer to the question. If you feel you have a pressing need to handle it yourself, we suggest you look at the source code for a number a of ORM's (See Doctrine on Github) and find the solution that best fits your scenario.
Thanks for asking a fun question, I appreciate it.
Every single dependency relationship within your class hierarchy must be accessible from outside world (shouldn't be highly coupled). For instance, if you are instantiating class A within class B, class B must have setter/getter methods implemented for class A instance holder in class B.
http://en.wikipedia.org/wiki/Dependency_injection
The furthermost problem I can see with your code - and this hinders you from testing it actually - is making use of static class method calls:
Provider::create('external::create-user')
$user = Provider_External::createUser()
$customer = Provider_Gapps_Customer::create($user)
$subscription = Provider_Gapps_Subscription::create($customer)
...
It's epidemic in your code - even if you "only" outlined them as static for "brevity". Such attitiude is not brevity it's counter-productive for testable code. Avoid these at all cost incl. when asking a question about Unit-Testing, this is known bad practice and it is known that such code is hard to test.
After you've converted all static calls into object method invocations and used Dependency Injection instead of static global state to pass the objects along, you can just do unit-testing with PHPUnit incl. making use of stub and mock objects collaborating in your (simple) tests.
So here is a TODO:
Refactor static method calls into object method invocations.
Use Dependency Injection to pass objects along.
And you very much improved your code. If you argue that you can not do that, do not waste your time with unit-testing, waste it with maintaining your application, ship it fast, let it make some money, and burn it if it's not profitable any longer. But don't waste your programming life with unit-testing static global state - it's just stupid to do.
Think about layering your application with defined roles and responsibilities for each layer. You may like to take inspiration from Apache-Axis' message flow subsystem. The core idea is to create a chain of handlers through which the request flows until it is processed. Such a design facilitates plugable components which may be bundled together to create higher order functions.
Further you may like to read about Functors/Function Objects, particularly Closure, Predicate, Transformer and Supplier to create your participating components. Hope that helps.
Have you looked at the state design pattern? http://en.wikipedia.org/wiki/State_pattern
You could make all your steps as different states in state machine and it would look like graph. You could store this graph in your database table/xml, also every provider can have his own graph which represents order in which execution should happen.
So when you get into certain state you may trigger event/events (save user, get user). I dont know your application specific, but events can be res-used by other providers.
If it fails on some of the steps then different graph path is executed.
If you will correctly abstract it you could have loosely coupled system which follows orders given by graph and executes events based on state.
Then later if you need add some other provider you only need to create graph and/or some new events.
Here is some example: https://github.com/Metabor/Statemachine

Naming of Listeners in Symfony2

I've read some guides / tutorials about Symfonys event system. But I am still not sure about the naming best practice. Unfortunatelly most documentations use default scenarios like login, etc. So here is an example from a game:
A command evaluations some kind of match result. It fires an appropriate event like this:
$dispatcher->dispatch('game_bundle.match_won', new MatchWonEvent($match, $winner));
Now I want to register several listeners to handle this event, like for example one for posting this to the winner's Facebook page and another one to book an achievement for the winner. In the examples I found the listener handling the login event was mainly called something like LoginListener, but shouldn't this name relate to the actual use of it instead of the event it is related to? Because now in my example I would need a MatchWonListener, but should that contain both the Facebook and the achievement logic? That would make the event system useless then... Wouldn't it be better to have one FacebookListener with an onMatchWon($event) and one AchievementListener with it's own onMatchWon($event) method? This would also make it easy to add more Facebook-related events into the FacebookListener for example.
I am confused about the naming in the samples and not sure about now. Am I getting it totally wrong?
There's no "best practice" on how to name events. However, if you name the listener after the event, I think that defeats the purpose of events altogether. The goal is to be able to let different parts of your system interact between each other without coupling and mixing concerns.
So considering you went this far of creating events to separate concerns, why would you go and mix all the different logics into one listener? In that case you might as well just do a direct call instead of dispatching an event.
I'm personally against names like "onMatchWon" because that doesn't describe what the method does. Let's say you want to listen to a match won event and update the achievements of the user who won. I'd probably have some user manager service or the sort with a method updateAchievements(MatchWonEvent $event). But I think that's more of a matter of taste, or convention if you're willing to.

How to implement Observer Pattern in PHP with global scope and persistance

The very basic idea of my goal is this:
User A submits a value via a form to submit.php
User B monitors the values submitted, which is updated via Server-Sent Event, pushed from updates.php.
submit.php handles writing the new value to the database, as well as notifying the observer object in updates.php.
Points of confusion:
Does each instance (session) of updates.php needs its own observer, as each user viewing the updates will be running their own instance of the script, or can they all share the same global observer object?
When the Subject Object loads, where is it going to get the observer objects? I can't store/put to sleep the observers, as they are active, right?
If I go with an ObjectStorage object, when the submit.php gets called and fetches it, are they observer objects actually the observer objects, by which I mean will calling their update method actually update the user's list?
How does I store/retrieve the ObjectStorage object from submit.php each time the form is submitted? Obviously I can't uses sessions, right? As those would be per-user?
Short version: Is there a way to get a global, persistant object containing the Observers on the Subject side where the Observers are live objects?
If there are better or simpler approaches to this idea (or if I'm just totally confused and need educating) please let me know. But I am not looking for a framework that can already do it all, as I'm trying to use this project to better understand the Observer pattern as an idea.
An important note for you to remember before the explanation:
A design pattern is a solution created to solve a specific language-related problem (limitation). They are not design rules of thumb in software architecture at a language level.
I'm not sure on how you can see the Observer pattern, but I'll try to help you anyways:
No. Session in your case means user instance. You should, somehow, work with single abstract Observers that will handle all the instances of updates. The global Observer object is the way to go;
Yes, they are active objects, since the Observers register themselves with the Subject. At some point you are gonna have to intercept them;
Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject’s state that it is responsible for monitoring. I guess you can figure that out from that;
That's really about implementation design. There is not a specific way to do it. You can try and see what suits you better;
Basically, yes, you can have a global Observer object, but that's not really the point of the pattern.
Try reading about the implementation of the Observer pattern and see if that helps you at all.
I would suggest that you investigate socket.io.

Categories