I’m trying to get some service (e.g. session) from outside of controller.
Please, explain how to do this right-way.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are many different ways, all having pros and cons.
First, every service is some kind of object, so you can always just create the object in question yourself. You may be forced to deal with many references, but it’s possible. This undermines the idea of Dependency Injection, so it’s not what you should do!
The second way is inject the service into your class:
This might be ok if you only use the class within your Controller. If you have more nested relations, like in MyClass, you create another class where you need the session, you might run into tight coupling (which is to avoid) as well as complexity issues.
The best way is to create your own service and injecting the things you need there. There are many documentations out there, so I’ll just give a short example using MyClass above.
Now your Class is as service (who would guess it’s that easy!) and you can use it within your controller:
Now you don’t have to think about constructor and how to get your objects, the DI-Container will do it for you. If you want to know more, read here.