Dependency Injection (DI) memudahkan testing, maintenance, dan decoupling antar layer.
Go
Gunakan uber-go/fx atau samber/do.
fx Pattern
// Module definition
var UserModule = fx.Module("user",
fx.Provide(NewUserRepository),
fx.Provide(NewUserService),
fx.Provide(NewUserHandler),
)
// Provide (constructor injection)
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
fx Module
Group module ke dalam internal/modules/ atau internal/domain/.
Laravel
Gunakan service container bawaan.
// Bind interface ke implementation
$this->app->bind(
UserRepositoryInterface::class,
EloquentUserRepository::class
);
// Inject via constructor
class UserController extends Controller
{
public function __construct(
private UserRepositoryInterface $users
) {}
}
NestJS
Gunakan module + decorator @Injectable().
@Module({
providers: [UserService],
controllers: [UserController],
})
export class UserModule {}
@Injectable()
export class UserService {
constructor(private repo: UserRepository) {}
}
Aturan
- Interface ke implementation: Kode depend ke interface, bukan class konkret.
- Constructor injection: Jangan pakai property injection / setter injection.
- No global state: Gak boleh pakai singleton / global variable kecuali via DI container.