How to inject dependencies into Yves controller? - spryker

I know that an instance of \Symfony\Component\HttpFoundation\Request can be injected into Yves controller action method. I know also that a path parameter can be also injected into controller action method. Is there a way to use constructor- or method-injection for the services needed in controller? Or using factory is the only way to get required dependencies into Yves controller?

I would say that using factory is the correct way for it. And it won't become problematic in future.
Any other option might become hack that will make Spryker upgrade problematic and time consuming.

Related

Symfony add logic to logout route

In a Symfony 5.0 Application I want to add custom logic for cleanup reasons when the user loggs out.
What I have currenty is what is described in the docs:
https://symfony.com/doc/current/security.html#logging-out
As the logout() function in the SecurityController is intercepted by Symfony it won't work to add logic there.
So - where CAN I add logic which is allways executed when a user loggs out?
Couldn't find anything in the docs so far...
IMHO the best option is to implement the LogoutHandlerInterface referenced slightly indirectly on the symfony docs you mentioned (it mentions the LogoutSuccessHandlerInterface, which has a comment regarding the LogoutHandlerInterface: "If you want to only perform some logout related clean-up task, use the LogoutHandlerInterface instead.")
To me, it feels like an event handler, but it doesn't use the event system, so ... whatever.
Nevertheless, the arguments provided to your LogoutHandler will receive a TokenInterface which has TokenInterface::getUser() which returns the current user. (dependency injection on the constructor should provide you with additional services and stuff)
The alternative would be to implement an EventListener for the kernel request event - which the LogoutListener of the symfony/security package uses to manage logouts. You would have to add the same logic as the LogoutListener and probably have to make it trigger before the LogoutListener, this is however a slightly more convoluted way and I would really use the LogoutHandler.

Dependency Injection or Service Locator - Symfony

I have started to go through Symfony2 code, studied a little bit small classes like Pimple and after few hours of examination have come to strange idea. The best start for this is to explain how I understand few terms, so:
Dependency
Something which is needed for another thing to work, like "engine" in "car"
Container
Object or class which is able to store a lot of another objects, like "engine","gearbox" or even "car"
Dependency Injection
Process in which every dependency is injected to object, so if I need "car" I know that I have to inject "engine","gearbox" and a lot of another stuff. Important is, that "car" don't create "engine", but "engine" is put inside "car"
Service Locator
Process in which object asks for another object, for example into the car there is inserted our container, and when car need to start it require from container "engine", so container return him "engine"
When i studied Symphony code, they start with dependency injection, but after some time I realize that when Controller is created, there is injected whole container and then you can use $this->get('serviceName') to get it, so it more looks like service locator, which according to few articles is anti-pattern.
Sow how is it? Is that line between DI and SL so small that it is sometimes broken? Or did I misunderstood something? If I use DI, do I need to insert every service into controller, so I know from outside what I use? Or can controller become in some cases container?
Your understanding of DI is pretty good. And yes, Symfony Controller does implement ContainerAwareInterface, and as you said, has a service locator role. But service locator isn't an anti-pattern. Each pattern has it's proper and improper uses.
Furthermore, Symfony doesn't enforce you in any way to use it's Controller. Your Controller can be a service. Hell, it can even be a function!
Here is one of the reasons why Controllers are implemented as service locators: Performance.
Let's drop car analogy and focus on real case that you'll encounter in 99% of projects: you need CRUD for a resource. Let's say you're building a Todo app and you need a RESTfulish controller to handle CRUD operations for Task Resource.
The least you need to have is a way to read all tasks and a way to add a new task, for that you need two actions: index (commonly named list too), and store (commonly named create too).
Common flow in Symfony would be this, in pseudo code:
indexAction -> getDoctrine -> getTaskRepository -> getAllTasks
storeAction -> getFormFactory -> createForm -> bindRequestDataToForm -> getDoctrine -> saveData
If Controller was a service locator
Index Action
When index action is executed, only service that will be resolved from the container will be ManagerRegistry (in this case Doctrine service). We will then ask it to give us task repository, and we'll do our operation with it.
Store Action
When store action is executed, we will do a bit more work: ask container to give us FormFactory, do some operations with it, and then ask it to give us Doctrine and do some operations with it too.
So summary: when index action is executed, only one service has to be constructed by service container, when update is executed, two will have to be constructed.
If Controller was a regular service
Let's see what our Controller needs. From the section above, we see that it needs FormFactory and Doctrine.
Now, when you just want to call index action to read all tasks from data storage, your controller will have to get instantiated by container. Before it can be instantiated, container needs to instantiate it's dependencies: FormFactory and Doctrine. Then instantiate controller while injecting those two into it.
So, you are calling index action which doesn't need FormFactory at all, but you still have overhead of creating it because it is needed for an action that will not be called at all in that request.
Lazy Services
To reduce this overhead, there is a thing called lazy service. It works by actually injecting a Proxy of your service into the controller. So, as far as controller is concerned, it got FormFactory. What it doesn't know is that isn't real FormFactory but instead a fake object which will delegate calls to real FormFactory code when you call some method on it.
Wrapping it up
Controller doesn't have to be a service locator, but can be. Making it a service locator can be a bit more performant and easier to bootstrap, but hides dependencies. Furthermore, it's a bit harder to test, since you'll need to mock dependency container. Whether you want to make your controllers services, functions or service locators is your choice and Symfony won't enforce you to use any of those ways.
In my experience, extending default Symfony Controller and having controllers be service locators is just fine as long as you don't write your business logic in them, but instead delegate all that work to services, which you get from container. That way, it's really unlikely that you'll have bugs in controller code (as methods will usually consist of 2-3 lines of code) and can get away without testing it.

Symfony2 Accessing a service from a non-service class

I want to access a service I've created (ServiceClass) from another class that I've created (ClassA). I've read a lot that the proper way to do this is to make ClassA a service and then inject ServiceClass, but class ClassA is not really a service in terms of functionality, it doesn't provide any global functionality, for me it's an Entity, so making it a service just so I can have access to other services doesn't seem right. Can anyone help me understand?
If it is an entity than it shouldn't need to know about any service. In ideal cases entities are just used to store data. You should rethink your class structure probably.
If you still want to go that way anyway, your only option is to declare it as a service or inject/set services when instantiating your class.
And yes, please provide code so we can suggest you what to do. This is just blind guessing because you provided very little info.

Where to place business logic is Symfony 2 model layer?

I'm moving my old codebase to the Symfony 2.2 framework.
In my old code, my Article entity has had a method getUrl(), which was returning a URL for current article.
In Symfony i have to use Router service to generate such an URLs.
I can't access Router from inside the Entity, cause it's a bad practice and not really supported by the framework.
I can call the router from the Twig template itself using Twig helper path() and provide all the arguments (from the Article instance) needed to construct the URL. But this approach is not very good, cause if i'll decide to change URL formatting rules - i will have to find all this calls and rewrite them (not very DRY).
I really want to save the business-logic encapsulation here and not to pull all the guts to the view layer.
How should i proceed in this situation?
Create an ArticleManager class in your service layer, and handle any business logic there. You can pass the router to it through dependency injection.
For your example, ArticleManager would have a getUrl(Article $article) method which would use the router instance (that you either injected through __construct or a separate setter method) to generate the Url based on properties of $article, and return it.
This method will ensure that your business logic doesn't pollute the view or controller layers.
Be sure to read up on the Service Container docs.

How to access 'templating' service not in controller

Ok, so the problem is:
I've got some 'order' entity, and it has 'status' property. On changing status, i wanted some other objects to be informed of this event, so i've decided to use Observer pattern. One of the observers notifies clients via email. Now i want to render Email text's from some of the twig templates. As i get from the Book, rendering templates in controllers are done with 'templating' service.
So the question as it follows: How can i access 'templating' service in my Observer class?
Specification:
I was advised, to implement my Observer as a service, but i'm not sure 'bout that. I've tried to solve this problem, and here is my options:
Use Registry. Solution that is straight and hard as rail. I guess it misses the whole point of DI and Service Container. Huge plus of this solution, is that i can access all common services from any point of my application.
To pass needed services from the context via constructor, or via setters. This is more like in Sf2 spirit. There comes another list of problems, which are not related to this question field.
Use observers as a service. I'm not really sure 'bout this option 'cos, in the book it is written, that service is a common functionality, and i don't think that observing entity with number of discrete properties is a common task.
I'm looking for a Sf2 spirit solution, which will be spread over whole project, so all answers with an explanation are appreciated.
As with any other service in a Symfony2 project, you can access it from within other classes through the dependency injector container. Basically what you would do is register your observer class as a service, and then inject the templating service into your observer service. See the docs for injecting services.
If you're not familiar with how Symfony handles dependency injection, I'd suggest reading that entire chapter of the documentation - it's very helpful. Also, if you want to find all the services that are registered for application, you can use the console command container:debug. You can also append a service name after that to see detailed info about the service.
Edit
I read your changes to the question, but still recommend going down the DI route. That is the Symfony2 spirit :) You're worried that your observer isn't common enough to be used as a service, but there's no hard rule saying "You must use this piece of code in X locations in order for it to be 'common'".
Using the DIC comes with another huge benefit - it handles other dependencies for you. Let's say the templating service has 3 services injected into itself. When using the DIC, you don't need to worry about the templating service's dependencies - they are handled for you. All you care about is telling it "inject the templating service into this other service" and Symfony takes care of all the heavy lifting.
If you're really opposed to defining your observer as a service, you can use constructor or setter injection as long as you're within a container-aware context.

Resources