Welcome Guest, Not a member yet? Register   Sign In
Why is it not recommended to use services in models and libraries?
#1

Looking at the CI4's documentation about the Services (https://codeigniter4.github.io/userguide...e-services) there is a quote that says:

Quote:It is recommended to only create services within controllers. Other files, like models and libraries should have the dependencies either passed into the constructor or through a setter method.


Why it's not recommended to use the Services directly into the Model or Library? Wouldn't it be easier to just invoke the service and get the data rather than to make extra setter methods or pass it to the construct function?
Reply
#2

No one forbids you, this is a recommendation.
CI4 is already a little behind modern methods (for example, DI containers, etc.). I think that's why having dependencies in Models is better than a direct call. This is especially important when writing tests with fake Services
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply
#3

Still don’t understand why. I think Services is great function. I can make my own services for commonly used classes and use the Services::func() wrapper to access them without creating new instance all the time. Why is that not recommended?

Thanks.
Reply
#4

You decide for yourself "do you need it?" A recommendation is just a tip.
Perhaps you will never encounter a problem when you need to replace ~1000 lines with services.
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply
#5

(11-04-2023, 09:05 AM)semprom Wrote: Why is that not recommended?

If you call Services in your class, the class depends on Services.
It means the class does not work at all without Services.
If you use the class, you must provide Services for it.

But if you inject the needed Service instance (not Services) into your class, 
you can use the class anywhere without Services.
It is more portable, and clean.
Perhaps it would be a little slower with Services.

However, Services is relatively simple because it is simply static methods to return Service instances.
So it will not be a major problem.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB