Open ryanmortier opened 5 years ago
a) Constructor injection:
i dont know. Personally, i only use it when there is no other solution and to keep my classes testable by avoiding hidden dependencies.
b) Method injection
Easily avoidable by using eloquent relations. or limit it to repositories (if you use them).
c) Facades
To be used as a tool for singleton and factory pattern
d) Global helper functions
If the function is totally independent from any other class and require only it's parameters. example:
function sum($a, $b) { return $a + $b; }
For Laravel global helpers: Use with caution, not everything is to be used anywhere or used at all. like you dont call request()
helper in model level
I personally use those depending on context:
In libraries
In application code
I think constructor or method injections lead to code that is easier to test. Having a facade or global helper within the class itself leads to tightly coupled code. Making it harder to test, refactor, etc. (doesn't mean impossible, but harder).
@alexkuc Not true. In fact, using facades is the easiest way for testing since facades where designed for easy testing in mind.
Also if you are using the new Octane/Swoole system instead of php-fpm, then you should avoid constructor injection completely, since it might leak data between requests.
So in current version its best to use Facades everywhere, unless you need support for non-laravel projects.
Facades must die.
If you use facades (e.g. Log
or DB
) you cannot write clear Unit test.
Always use DI and then you may pass mocks into class you testing.
Remember, Unit test must extend TestCase
from PHPUnit
namespace.
@zlodes
Facades must die.
I wouldn't go this harsh. I believe helpers and facades in Laravel were made for RAD and POC code. When you have clear business and technical requirements, it must makes sense to spend time writer leaner and cleaner code. But when you are improvising or dealing with high level of uncertainty, I think that would lead to waste. Imho.
I was just wondering what the best practices are or what the community's thoughts are on when to use:
a) Constructor injection b) Method injection c) Facades d) Global helper functions