DEV Community

Cover image for Membuat Custom Helper Codeigniter 4
MedanInCode
MedanInCode

Posted on • Originally published at medanincode.com

3 2

Membuat Custom Helper Codeigniter 4

Helper biasa digunakan untuk mencegah kode yang berulang-ulang di controller dan view kita.Helper berlandaskan kepada metode DRY.Fungsi di Helper bisa dipanggil di controller maupun view.

Langsung saja ke tahap pembuatan custom helper.

Membuat Custom Helper

Buat di folder app/Helpers/ file bernama my_helper.php ,namanya bebas terserah kita.
Misalnya kita isi dengan fungsi yang pasti sering digunakan yaitu format rupiah.Langsung saja isi Helper dengan kode dibawah.

<?php
function format_rupiah($angka){
  $rupiah=number_format($angka,0,',','.');
  return $rupiah;
}
?>
Enter fullscreen mode Exit fullscreen mode

Menggunakan Custom Helper

Ada dua cara memanggil helper pertama secara global dan manual di masing-masing controller.

Memanggil Secara Global

Buka file app/Controllers/BaseController.php lalu cari bagian ini

protected $helpers = [];
Enter fullscreen mode Exit fullscreen mode

Ubah menjadi

protected $helpers = ['my_helper'];
Enter fullscreen mode Exit fullscreen mode

my_helper merupakan nama file helper yang kita buat tadi.

Memanggil Secara Manual

Buka file controller letakkan di fungsi mana kita akan memanggilnya

helper(['my_helper']);
Enter fullscreen mode Exit fullscreen mode
Menggunakan Fungsi Helper

Untuk menggunakannya kita tinggal memanggil seperti kode dibawah ini baik di controller ataupun di view

echo format_rupiah(10000);
Enter fullscreen mode Exit fullscreen mode

Sekian tutorial kali ini.Selamat Belajar

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay