Get Controller within Event or Model

Hello,

I instantiate a component within AppController. Working fine. Now I call Events in model afterSave/afterDelete. This event-class lies in src/Event/. Within that Event-Class I need to access the instantiated component to send Messages.

The Problem is, that all the components setup is (already) done in AppController and this component shouldn’t be created more than once because it opens connections to other services.

I hope you know what I mean. In short: How can I access the Component or Controller from the Event-Class fired by a TableClass.

Thanks in advance

How can I access the Component or Controller from the Event-Class fired by a TableClass.

Generally you can’t do that. You might want to either use additional events to pass signals up from the Table to the Component instead, another option might be to use a standalone service class that both the component and relevant table classes could use.

Hi thanks for your answer. I thought about it and worked a bit on it, but it seema like I didn’t get the idea behind your answer. From the table, I can’t instantiate the component again, because it is done already by AppController (I don’t want to instantiate it twice because of the NetworkTraffic and open ports and so on…).

So I must find a way to talk from the table class with the component. And I want to use the event system.

Do you have examples for your possible solutions? Sry, but i really didn’t get it.

Thanks again!

Hello again.

In addition to my last answer: What do you exactly mean by “service class”. Sorry I didn’t make any progress on this topic.

Based on this comment: https://github.com/cakephp/cakephp/issues/7249#issuecomment-233423113

I have the same question for @markstory :slight_smile:

Hello again,

yesterday, I “talked” to hmic and he told me to delete/remove the component completly and to create a custom lib. Is this what you meant, @markstory ?

And @markstory: What did you mean by “use additional events to pass signals up from the Table to the Component”. I would prefer this method instead (I think).

I’ll try to do so, but I don’t know, if this will work. Sometimes, I want to pass some variables or other data to this notification (such as the user-id which invoked the afterSave-event etc.)

Please help me/us :wink:

Yes an custom library/class is a functionally equivalent to a service class to me. In the applications I work on. Service classes glue a few different layers together and provide the ‘application model’. For example, I’ll use a service object contain the interactions of ORM records, 3rd party systems and queues (RabbitMQ). The service object allows my controllers and shells to use a simple interface, and doesn’t require code duplication or complex event listeners.

Some blog posts that explain this idea some more