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

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay