Symfony2 Event Dispatcher (in theory) - php

I do understand the concept of the Observer Pubsub and MVC pattern. I use it in jQuery for instance. Symfony documentation also seems decent, so the usage of the component isn't really an issue but the concept is kinda confusing for me. Could you point some real-life examples (dummy code would be awesome) of using this pattern in Symfony? Can I use it in several different controllers or controller's methods only?

I think Form.php is a good example. If you look at bind method (which is called during bindRequest method call) it dispatches various events. For info about those events take a look at this answer. Also check this cookbook entry for adding event listener.
Edit: It seems there is a cookbook section on event dispatcher. Check here.

I think you should go through
https://github.com/beberlei/AcmePizzaBundle
it shows you how to build forms using form builder and interact with the database.

Related

What is the best practice for using services in Symfony instead of Controllers and not only there?

Well i'm learning Symfony (3.3) and i'm little confused about Service Container. In first tutorial the lector show register, login, add post, edit, delete methods in User, Article Controllers. Then in other tutorial, they show same methods but use Service Container (User and Article services) with User and Article interfaces. So .. what is the best practice for implementation in Services instead of Controllers.
I would like to add to Alexandre's answer that it is considered best practice to keep your controller 'thin'. In other words, only put code in your controller that really has to be there (or if it only makes sense to put it in your controller).
Services are like tools you can use in your application. A service in an object that helps you do something. In one service, you can have many functions. I think the best way to understand the difference is that a controller is for one specific action, a service can be used in many actions. So if you have parts of code that you want to use in more than one controller, create a service for it. And for the sake of re-usability, create functions in your service that do only one thing. This makes it easier along the way to use these functions.
the "best practise" depends on what you want to do with the Service. If you build an REST-Api you might want to do Database-Operations in Controller. Why? When you rely on the SOLID-Pattern you want to reduce or eliminate redundant code. If you code a real REST Api you don't have redundant code because each REST-Verb will do a different query/thing.
So in a non-REST-Api-application you will have a lot of redundant code. You do the same things/services on different pages/controller-actions. So the best thing is to implement all the business-logic in services to have it only one time in one place. If you have a lot of individual queries place them into repositories. If you have business-logic that fit's into an entity-class place them there. So in my opinion you can choose a thick controller/no service design in API's and a thin controller/thick service design in classic symfony front-/backend applications.
But one more thing: there is no totally wrong way to design an application. But if you work with other people or want to run the application longer than a month (without having trouble to maintain it) you should pick a common design-pattern.
Controller must implement the application logic like check if it's a post request or if a form is submit etc...
Never use DQL or any SQL Request directly inside a controller !
EDIT In the example i use a find method inside the controller because it's a Repository method but i parse the result inside slugify (my service method)
Services contains business logic like formatting phone numbers, parse some data etc...
Of course you can inject a repository inside a service and call your methods inside it.
An example:
//This is a fictive example
public function indexAction(Request $request) {
//Application logic
if(!$request->get('id')) {
//redirect somewhere by example
}
$article = $this->getDoctrine()
->getRepository(Article::class)
->find($request->get('id'));
//Business Logic
$slug = $this->get('my.acme.service')->slugify($article->getTitle());
}
Hope this helps

Yii trigger component event from controller action

I'm trying to create a method where I can trigger an event from a controller action (sending parameters with it), and have multiple components (in the same, or in another module) to listen that trigger and execute some random code (maybe some sanitised string or something)..
Is there a way to create such system with Yii Events? Or i'll need to work around something else?
Thanks
Sure,
Yii has a nice event system using CEvent. Have a look at Events explained tutorial.
You can combine it with yii Behaviors, here's another good tutorial if you are interested in Behaviors & Events.
Behaviors are a way of adding methods to a Class without php limitations of class extending since you can attach several behaviors to a same class.

How (or WHERE) to use the EventManager of the Zend Framework 2?

I am trying to use the new Eventmanager of the Zend Framework 2. I do understand the basic usage. But i´m not sure how to use this in a real project or rather where to go with the code.
For example:
In the introduction from Rob Allen (link above) he triggers two events in the "findById" Method. Where should the code for the listeners go to? In my opinion it doesn´t make sense to put this code also in the PhotoMapper class or am i wrong?
I confess that I have not played with it strongly yet, but I think you are right that the listener code should probably not be in the mapper. Rather, it can stand alone in an external class so it can really be a single-responsibility object - handling the events to which he subscribes - and the code can stay as DRY as possible.
As a first step, we can define what the listener needs to to do his job. Some things he knows on instantiation, others need to passed when the event is triggered.
For example, for a cache listener, I might instantiate him at Bootstrap with info about where to cache, lifetime, etc. Perhaps even grab a cache instance fully configured and ready to go from the cachemanager resource. These could be constructor params for the listener object.
Then, still probably at Bootstrap, I would register this listener with the event manager, subscribing to your event and attaching the method you wish to run when the event is triggered. Of course, that method signature needs to be compatible with the information that the event manager will give you.
I guess the idea is that this listener object has the potential benefits of:
being single-responsibilty, so lower complexity and easier to test
hopefully being sufficiently general so that this single listener can handle multiple events.
There is a little wrinkle here. It might seem like unreasonable performance hit to instantiate and register a listener just on the chance that some downstream process might trigger the event to which he is subscribed. That's where static listeners come in. Again, the registration is done early (like Bootstrap), but the listener is not instantiated until he is really needed.
Disclosure: I might have this completely wrong. So if someone wants to straighten me out, that would be great. ;-)

Access Symfony2 service layer in Doctrine entity?

I'm sure the title is pretty descriptive, but for a more in depth question: How does one access Symfony2's service layer for use in Doctrine's lifecycle callbacks? I plan on utilizing these callbacks to register an entity in my search index (which is managed by another service) every time it is created/updated/deleted.
There are a couple of things that come to mind, though, so I might as well ask them as well...
Is this illegal, bad practice, or just plain terrible? Is there another solution to hooking logic involving services into the entity's lifecycle or should I decouple them altogether?
I dig any advice and am down to try new things.
Check out this cookbook entry.

Kohana beginner question: controllers, hooks and vars - Oh my!

I'm new to the MVC concept, and somewhat new to PHP.
Question 1
Before every controller is loaded, I’d like to run a function which checks to see if a database-table exists. Is the proper way to do that with hooks?
Question 2
Before every controller is loaded, I’d like to set a few variables which are determined by a call to the db. How/where is that supposed to be done in a MVC (Kohana) setup?
Edit: Regarding Kohana v2.3.4
For Question 1 & 2, I would use hooks for these. Hooks allow you to have code executed at various times throughout the framework's startup and tear down phases. Checkout the documentation page on hooks on Kohana's site. The events documentation has all the events listed that you can use throughout the framework.
Question 3: You don't ever really have to use a constructor in your controllers. One reason to do it may be if you have several actions that need the same object instances and things like that, you can create them once in the constructor.

Categories