Where to place EventDispatcher in Symfony2 and how to use it with Annotations? - configuration

I am starting developing with Symfony2 framework and I like to use the Eventdispatcher. Now I have three questions I could find an answer with google yet.
Where I place the dispatcher so it is accessable from everywhere in
tha app?
How I can configure customevents? Should I place all in one file or
one for each bunble?
How much effort is it to configure it with annotations, i.e
#Event("some.event")? Is that possible?

General
I might suggest the Symfony 2 documentation on the EventDispatcher as a good starting point, assuming that you mean you wish to provide custom events rather than a custom event dispatcher.
Symfony2 Internals - The Event Dispatcher
Location of Events
In terms of location, an 'Event' folder within the appropriate bundle is a good choice. It is likely that the actual dispatching of the event will take place only within the bundle context, whereas listeners may reside elsewhere. This is however a separate topic and of minimal relevance as they simply subscribe to the event's string-name (e.g., 'store.order' to borrow the documentation's example) and only require knowledge of the Event's interface/type.
So you might have an Event called 'Foo' within the 'Bar' bundle in 'Zap' namespace:
namespace Zap\Bar\Event;
use Symfony\Component\EventDispatcher\Event;
class FooEvent extends Event
{
// ...
}
When you then come to dispatch an event from within your bundle, you might choose to use the event identifier 'zap.bar.foo', and of course you can then register listeners from elsewhere to be notified on this identifier as you see fit.
Accessing the Event Dispatcher
Where you wish to access the primary EventDispatcher instance, acquire access to the Dependency Injection Container and retrieve the 'event_dispatcher' service. A simple approach is to have your class extend 'ContainerAware' and then retrieve the dispatcher with
$dispatcher = $this->container->get('event_dispatcher');

To answer your first question:
Where I place the dispatcher so it is accessable from everywhere in tha app?
Actually, there is already preconfigured event dispatcher service accessible, as #jstephenson pointed out, by calling $dispatcher = $this->container->get('event_dispatcher'); so you don't have to create your own instance anywhere.
However, if you need your own event dispatcher, you can simply configure it in your services configuration file (i.e. services.xml) of your bundle like this:
<service id="my_dispatcher" class="Symfony\Component\EventDispatcher\EventDispatcher" />
You can of course use your own dispatcher class as long as it implements EventDispatcherInterface.

Related

MVVM - Share encapsulated model with other VMs

In my Windows Phone App there's a simple hierarchical model consisting of a class containing a collection of other domain objects.
In my xaml i have declared an ItemsContainer control that renders the items in the above mentioned collection as simple rectangles.
Now, at the VM level i have a structure that resembles my model with a parent VM having a collection of children VMs. Each child-VM encapsulates its own model.
Whenever the user taps the view bound to a child-VM a method of the parent-model object should be invoked taking the relevant child-model as parameter. This will in turn change some internal state that will be reflected (possibly) on all the child-views (not just the tapped one).
SO... given that i'm using the MVVM Light framework my current implementation is as follows:
Child-VM exposes a command
The command Execute method will use the messenger to notify the parent-VM of the tap event. The message (GenericMessage class) content will be the domain object encapsulated by the VM
The parent-VM executes the method of the parent-model using the message content as parameter
If the operation succeeds the parent-VM sends a new message to inform child-VMs of this fact. Once again the message content is the model object used as parameter in the method that was just invoked
Child-VMs raise a couple of PropertyChanged events that, finally, will update the bound views
It works but i fill it's a bit cumbersome. The thing that bugs me the most is the fact that when a child-view is tapped the associated VM will broadcast its encapsulated model object. Do you feel that there would be a better way of implementing such a system?
Thanks in advance for your precious help
Could you not just put the command on the parent viewmodel and pass the child viewmodel as the command parameter?
The parent view model can then just call methods on the child viewmodels to update them. I'm not sure I see the need for all these messages?

Resolving a dependency while supplying values for downstream dependencies

I've been running into endless problems attempting to use Windsor with Web API and injecting HttpRequestMessage into downstream dependencies of a controller. Since I've tried all the matching answers on Stackoverflow, I'd like to ask the question in a different way:
In Castle Windsor, how can I resolve a component instance while supplying a value for a downstream dependency? That is, the supplied value is required by a component that is required by the component being resolved.
For context, I'm trying to inject HttpRequestMessage so that I can use it to resolve the request context (primarily to resolve an absolute URL).
Edit I'd also like to point out that I don't currently have a dependency on Web Host / System.Web and I'd rather not change that.
A proper approach is to
Create IMyDesiredRouteParameterProvider
Implement it. Get the current request inside it and get the url
Register it and inject it in the desired dependent class via constructor.
I made myself such an implementation and I can say that this way it works fine. You can make Web.Infrastructure assembly and put the implementation there. Or put both the interface and the implementation there if you are going to reference it from another web module.
using System;
using System.Web;
namespace RouteParameterProvider
{
interface IMyRouteParameterProvider
{
string GetRouteParameter();
}
public class ControllerActionMethodRouteParameterProvider : IMyRouteParameterProvider
{
public string GetRouteParameter()
{
string Parameter = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"] as string;
if (string.IsNullOrEmpty(Parameter))
{
throw new InvalidOperationException();
}
return Parameter;
}
}
}
You can get every possible thing that the Request Context contains from :
HttpContext.Current.Request.RequestContext
And it will be better if you rethink your design decision :
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
Containers are to be initialized at runtime and then used to resolve.
I need HttpRequestMessage to be regstered prior to creating each
instance of SomethingController so that it will be available down at
the LinkGenerator layer.
It sounds like you want to register an item with the container at runtime, post-startup. In general, this is not a good practice--registration should be a discrete event that happens when the app is fired up, and the container's state should not be changed during runtime.
Dependency Injection is about resolving service components, not runtime state--state is generally passed via methods (method injection). In this case it sounds like your LinkGenerator component needs access to the ambient state of the request.
I'm not that familiar with HttpRequestMessage, but this answer seems to show that it is possible to retreive it from HttpContext.Current. You could make this a method on your LinkGenerator class, or wrap this call in a separate component that gets injected into LinkGenerator (HttpRequestMessageProvider?). The latter would be my preferred method, as it allows LinkGenerator to be more testable.
Given the lack of a clean way of doing this and Web API not providing information as to the hosted endpoint beyond per-request context objects, I ended up injecting the base url from configuration.
Is this library by Mark Seemann the answer? In the description he writes explicitly :
This approach enables the use of Dependency Injection (DI) because the
request can be injected into the services which require it.
Then gives an example :
// Inside an ApiController
var uri = this.Url.GetLink(a=> a.GetById(1337));
By which you can then pass the URL down the road in the service that you have injected in the controller.
UPDATE :
Mark Seemann wrote about the same exact problem here:
"Because HttpRequestMessage provides the context you may need to
compose dependency graphs, the best extensibility point is the
extensibility point which provides an HttpRequestMessage every time a
graph should be composed. This extensibility point is the
IHttpControllerActivator interface:..."
This way you can pass request context information to a component deep in the object graph by getting from the HttpRequestMessage and passing it to the DI container.
Just take a look at the interface of IHttpControllerActivator.
The WEB API framework gets the IHttpControllerActivator through DependencyResolver. You probably already replaced it by your CastleWindsorDependencyResolver. Now you have to implement and register your HttpControllerActivator and register it.
When the WEB API framework gets IHttpControllerActivator from DependencyResolver (your Castle Windsor DR) and calls IHttpControllerActivator.Create() it will pass you the HttpRequestMessage. You can get your info from there and pass it to the your CastleDR before you call Resolve(typeof(MyController)) which will resolve the whole object graph - that means you will have MyHttpContextInfo to inject in your XYZComponent deep in the resolution stack.
This way tou are passing the arguments in the last possible moment but it is still possible. In Castle Windsor I make such passing of arguments though CreationContext.AdditionalArguments["myArgument"];.

How do I attach a global event listener?

I am working on an AIR application:
The main window is like a dashboard. With the menu bar, I can open other windows with dashboard details. When I close these, I'd like to refresh the main window.
I tried to use an event listener, but the result is not good. If I open detail windows directly from the main window, I know how to add an event listener - and it works - but I don't know how to do it, if the detail window is opening from the menubar!
Thanks for helping me.
A Singleton is what you are looking for. Just put an event dispatcher inside and you will be able to listen from everywhere in the application.
A Singleton is like having a unique instance of an object in memory, so anyone modifying a variable inside that object ( or sending events throught ) will be modified for everyone.
Here is an example of code on how to use it.
http://life.neophi.com/danielr/2006/10/singleton_pattern_in_as3.html
Note: Singletons are powerful and dangerous at the same time, there is a lot of talk about how to use them, please read a little more about that if you are considering building a big project.
Hope it helps!
The issue is that you're performing business logic from a View. Don't do this. Instead, dispatch an event from each menu rather than directly opening the window from within it. Listen for those events at a higher level, and then you can either directly listen to the new windows you have opened, or you can create a base window Class that exposes a variable of type IEventDispatcher. If you populate that variable with the same event dispatcher, what you wind up with is called an "event bus," and you can listen on that for events.
This architecture requires a little more thought than using a Singleton, but it avoids the tight coupling and other issues you'll run into by introducing one into your project.
You can listen to an object (EventDispatcher) directly by adding an event listener to it, or if the dispatcher object is on the displaylist, such as a Sprite, you could listen at the stage level with the capture parameter set to true.
But the main caveat is that the dispatcher must be on stage for you to catch this event.
Your main window listens to stage (with capture = true):
stage.addEventListener("MY_CUSTOM_EVENT", handle_custom_event, true);
private function handle_custom_event(e:Event):void
{
var sub_window:Object = e.target;
// do something to your sub_window
}
Your sub window can dispatch events like this:
dispatchEvent(new Event("MY_CUSTOM_EVENT"));
But (ab)using the stage as a message passing infrastructure for custom events in this way is a little messy. You could consider a more formal message passing architecture if you really want this kind of communication. Even a static MessageBus class would at least quickly help you identify where you use this in your codebase. Either way, you'll have to be careful about references and memory leaks.

What exactly this method do ? addActionListener

What exactly will this addActionListener Do.....we we call button.addActionListener(this) what will happen
It basically adds this (the current object) to a list of objects that will be notified when the component has an action performed on it, such as a button being pressed.
It's a way of registering your interest in what is happening to the component and is useful in that you don't have to keep polling a component to check its status.
Your object (or class, really) simply implements the interface methods for listening (such as actionPerformed) and that method will be called for each event that happens.
The Java tutorials have a large variety of different articles on the various listeners that you're likely to use.

Windsor Castle: Hooking up to container's resolving and releasing mechanism

I'm trying to implement automatic registration of my listeners to a singleton event aggregator when listeners are created by the IoC container - basically what Jeremy D. Miller is doing, but with Castle instead of StructureMap.
So I want to be able to "intercept" Windsor's object creation mechanism and, if the object supports the marker interface (let's say IListener), call the Subscribe method to an EventAggregator (which is also registered in the container) to make the newly created object a subscriber to events. Also, before the object instance has been released by the container, I want to be able to unsubscribe it.
I'm a little bit confused about what mechanism in Windsor Castle I should use to achieve something like this? I started looking at IInterceptor interface, but it seems to intercept all calls to the object, which is not what I really need (and want to avoid for performance reasons).
IKernel exposes various events like ComponentCreated and ComponentDestroyed which you can use to build that. There are many samples on the web.
Otherwise you could just use the event wiring facility, but it's not convention based.
You could also use OnCreate like this:
container.Register(
Component.For(typeof (Foo)).OnCreate(
(k, c) => {
// ...
eventAggregator.Subscribe(c);
// ...
}));