Belajar Method Chaining dan Implementasinya dalam PHP

Belajar Method Chaining dan Implementasinya dalam PHP

Create: SaldiSaldi | Kamis, 30 Maret 2017 | 17:31:23 WITA | dibaca: 1546

https://static.cdn-cdpl.com/source/5/oop-image(700x350-crop).jpg 

Method chaining merupakan salah satu konsep yang ada dalam paradigma OOP untuk mengikat / merantai method. Disini kita dapat memanggil lebih dari satu method untuk satu kali operasi dengan mengolah object yang sama. Setiap method tersebut berperan mengubah nilai property dalam object tersebut dari satu bentuk ke bentuk lainnya. Oleh karena itu method tersebut sering disebut mutator. Konsep chaining ini sendiri sudah diimplementasikan dalam berbagai bahasa pemrograman yang mendukung OOP seperti Java, Python, Javascript, Ruby, dan PHP.

Manfaat dari penggunaan method chaining adalah membuat kode yang lebih enak dibaca. Coba perhatikan contoh kode berikut ini.

// Tanpa chaining

$object = new Class();

$object->method_satu();

$object->method_dua();

$object->method_tiga();

 

// Dengan chaining

$object = new Class();

$object->method_satu()->method_dua()->method_tiga();

Nah, alih-alih memanggil method di beberapa baris kode, kita dapat membuat rantai method dalam satu baris kode. Dengan demikian kode akan terlihat lebih pendek.

Praktek Method Chaining

Mari kita coba membuat method chaining sederhana dengan menggunakan PHP. Kita akan membuat sebuah kelas bernama "StringMutator" yang berfungsi memanipulasi string. Dalam kelas tersebut, terdapat tiga method yang fungsinya sudah tidak asing lagi di telinga kita.

1.     Bold, menebalkan kalimat

2.     Italic, membuat kalimat menjadi cetak miring

3.     Underscore, menambahkan garis bawah dalam kalimat

Struktur kodenya akan terlihat seperti ini :

class StringMutator {

    // Property untuk simpan nilai-nilai mutasi

    protected $word;

 

    public function __construct($word) {

        // Konstruktor

    }

 

    public function bold() {

       // Menebalkan kata

    }

 

    public function italic() {

       // Membuat cetak miring

    }

   

    public function underscore() {

       // Menambahkan garis bawah

    }

   

    public function get() {

       // Mengambil nilai mutasi akhir

    }

}

Bisa dilihat kita membutuhkan satu property bernama $word untuk menyimpan nilai mutasi. Di baris selanjutnya kita butuh sebuah magic method construct untuk mendefinisikan kata yang mau diolah ketika object diciptakan. Selanjutnya kita butuh 3 method (Bold, Italic, Underscore) untuk kemudian kita isi operasinya.

Oke, mari kita modifikasi kelas dan mengisi setiap method dengan operasi sebenarnya. Pada kelas ini kita akan menambahkan operasi bold, italic, dan underscore dengan cara memodifikasi string dengan menambahkan "html" saja, kurang lebih hasilnya seperti ini :

class StringMutator {

 

    protected $word;

 

    public function __construct($word)

    {

        $this->word = $word;

    }

 

    public function bold() {

        $this->word = '<b>' . $this->word . '</b>';

        return $this;

    }

 

    public function italic() {

        $this->word = '<i>' . $this->word . '</i>';

        return $this;

    }

   

    public function underscore() {

        $this->word = '<u>' . $this->word . '</u>';

        return $this;

    }

   

    public function get() {

        return $this->word;

    }

}

Perhatikan method bold, italic, dan underscore yang kita buat. Setiap operasinya hanya meng-override nilai $word dan menyisipkan karakter html. Inilah salah satu contoh mutasi nilai. Perhatikan juga akhir dari setiap method, ada kode return $this;. Kode tersebut berfungsi mengembalikan object untuk kemudian dioperasikan lagi pada method selanjutnya. Dan terakhir method get() yang berfungsi untuk mengembalikan nilai final.

Mari kita coba class tersebut, kita akan mengolah string ini "Saya Belajar Method Chaining". Penjelasannya juga saya tambahkan di bagian komentar :

...

$word = 'Saya Belajar Method Chaining';

 

// Membuat object dan mendefinisikan string yang akan diolah

$string_mutator = new StringMutator($word);

 

// Contoh 1

// Operasi bold

$result = $string_mutator->bold()->get();

echo $result;

 

echo '<hr/>';

 

// Contoh 2

// Operasi bold + italic

$result = $string_mutator->bold()->italic()->get();

echo $result;

echo '<hr/>';

 

// Contoh 3

// Operasi bold + italic + underscore

$result = $string_mutator->bold()->italic()->underscore()->get();

echo $result;


Nah, hasilnya akan tampil seperti berikut :

 Contoh 1 menghasilkan operasi bold saja, contoh 2 menghasilkan operasi bold ditambah italic, dan terakhir output contoh 3 mengasilkan semua operasi.

Demikian contoh sederhana dari penggunaan method chaining. Jika ada pertanyaan silahkan isi kolom komentar. Semoga bermanfaat!

 

 



31 KOMENTAR

fake yeezys | 29 Juli 2017 || 11:13:53
" I still liked this article, good, good content, and unique design.Thank you for sharing the article. "
custom essay writing service | 04 Agustus 2017 || 13:38:35
" The article you have shared here very awesome. I really like and appreciated your work. I read deeply your article, the points you have mentioned in this article are useful. "
True Skate Apk Full Unlocked | 04 Agustus 2017 || 18:46:53
" New how to get all True Skate Apk all Skateparks free no jailbreak required youtube. Download True Skate APK Android Cracked for Free, Find a lot of best paid android apps and games cracked for any Android tablet and smartphone.True Skate APK Patched Full Unlocked Infinite Money 1.4.15. "
write my essay | 08 Agustus 2017 || 13:34:09
" 've installed dns, and cpd servers i'm using windows 2003 server. I need help with the configuration when i entered the LOOKUP> cm i had a message saying (domain unknown), also the dns console did not work, always Waiting to be activated. " "
online apps | 08 Agustus 2017 || 16:03:18
" Get Upto 80% Off On Online Shopping in India.Find the top Shopping apps and games for Android devices.Build Android App online or make your own free Google Android App online. "
Happy room | 19 Agustus 2017 || 11:14:16
" Nice! I want you to thank for your time! I like your visit regularly... "
Top Engineering College | 30 Agustus 2017 || 18:08:52
" The idea is to focus on facts and try and define a baseline problem to share. "
kolam hias | 13 September 2017 || 10:27:10
" mantap gan "
Sai baba images | 18 September 2017 || 23:11:01
" https://lordimageswallpapers.com/shirdi-sai-baba-images.ht ml "
root checker apk | 21 September 2017 || 23:02:22
" Root Checker is an Android Application which allows you to check whether your Android phone or tablet is rooted or not "
a10 | 02 Oktober 2017 || 14:01:38
" Hi, your blog is truly flawless and unique. "
color switch | 02 Oktober 2017 || 14:01:59
" Good content, but it would be better if in future you can talk about more about this subject. "
animal jam | 02 Oktober 2017 || 14:02:15
" Really very perfect your article and blog post. "
Apple iphone 6S dealers in delhi | 03 Oktober 2017 || 17:53:49
" Apple products are revered for its quality, precision and great design. SRSG started its operations as Apple technology partners in the year 1997. "
starfall | 07 November 2017 || 21:07:20
" This is extremely helpful info!! Very good work. Everything is very interesting to learn and easy to understood. Thank you for giving information. "
Fantastic good from you, man. I have understand your suff previous to and you're just extremel | 08 November 2017 || 17:48:02
" Fantastic goods from you, man. I have understand your stuff previous to annd you're just extremely magnificent. I actually like what you have acquired here, really like what you're saying and the way in which you say it. You make it entertaining and you still take care oof to keep it wise. I cant wait to read far more from you. This is really a great site. "
obat aborsi | 08 November 2017 || 18:33:41
" thanks kakak "
Acting school in Delhi | 23 November 2017 || 18:00:49
" Moonlight Films and Theatre Studio operates under the Moonlight Films and Theatre Society , a non-profit association whose goals are to spread knowledge of and interest in theatrical and media arts through education.<br> "
obat pembesar penis | 28 November 2017 || 07:32:20
" thanks "
entertainment survey | 08 Desember 2017 || 22:53:24
" The Six Flags Customer Feedback Survey is all about knowing the customer satisfaction on their offerings or the services. "
https://myonlinebillpayments.org/ | 29 Desember 2017 || 18:22:40
" Did you ever hear about the Bed Bath and Beyond online platform? If not then you need to look at it right now because it is an online platform which you can sop of anything you want. "
Rental Mobil Surabaya | 04 Januari 2018 || 23:05:49
" informasi ini sangat berharga bagi saya. "
Vimax | 12 Januari 2018 || 06:47:37
" thanks you infona "
Voyance amour en ligne | 16 Januari 2018 || 18:29:19
" Very interesting information, worth recommending. However, I recommend this. "
storspelare casino | 03 Juni 2018 || 23:43:23
" it is important to test the quality of the product prior to investing a lot into them. "
storspelare casino | 03 Juni 2018 || 23:43:54
" it is important to test the quality of the product prior to investing a lot into them. "
gmail sign up | 05 Juni 2018 || 13:39:55
" Inilah yang saya cari. Hasilnya sangat bagus. Implementasi dalam PHP lebih mudah karena posting ini. "
Reset AOL Mail Password | 23 Juni 2018 || 17:21:21
" Reset AOL Mail Password – If you are a user of AOL Mail then you are aware of a great many features of AOL Mail and must have experienced them. The AOL Mail has very user-friendly ways to deal with the issues of their customer’s issues too. Such as in case you forget your password and want to change it for good. You can follow these steps to Reset AOL Mail Password. "
norton.com/setup | 23 Juni 2018 || 17:24:11
" Norton, the world’s largest security software provides high-end protection against all kinds of threats and viruses lurking in the internet marking. These viruses, Trojan horses, scams and other malicious the software can harm important data and steal your confidential information (while accessing your bank account online). To get rid of this security issue, Norton has come up with a range of security software for both consumers and business PCs. You can choose any Norton security software from those mentioned below as per your specific requirements. "
chargeback representment | 23 Juni 2018 || 17:24:54
" Once there is an actual chargeback to your account we use available tools to take massive defensive action. The main tools we have to work with are documents and time. Defending chargebacks is a matter of quick and thorough communications with all the banks involved. "
gangstar vegas mod apk latest | 27 Juni 2018 || 00:23:03
" <a href="https://gangstarvegasmodapk.net/gangstar-vegas- mod-apk-latest-version-download/"> gangstar vegas mod apk latest </a> download free version "



ISI KOMENTAR

NAMA

WEBSITE

KOMENTAR


Captcha Sepakbola
Apakah anda manusia?Lebih baik lagi kalau anda menyukai sepak bola
Sebutkan pemain sepak bola disamping:

Captcha Sepakbola by codingwear








  • $DCC = NEW XXI("Solidaritas","Loyalitas","Kualitas");
  • PELATIHAN KAMPUS
  • Pelatihan Komputer (DIGITAL SCHOOL)
  • Study Tour GoTv
  • IT FUN