-2

I want to know about method chaining. Recently I have used method chaining in Laravel, it's working fine.

My Model name was Posts so when I want to select all names from posts it returns all names.

Posts::select('name');

And when I call below function to get one records it gives only one record.

Posts::select(name)->first();

I want to implement same scenario in my own class. I have a class of image uploading.

If I will upload only a file, it will be

Image::upload('pic')

But If I upload image with resize and watermark.

Image::upload('pic')->resize(200, 300)->addwatermark('image/logo.png');

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zartash Zulfiqar
  • 93
  • 1
  • 3
  • 13
  • Possible duplicate of [PHP method chaining?](http://stackoverflow.com/questions/3724112/php-method-chaining) – Bert Aug 20 '16 at 06:57
  • The question is not same! first read then comment and vote. Thanks! – Zartash Zulfiqar Aug 20 '16 at 07:02
  • There's not even a question in your post. I see "I want to implement same scenario in my own class.", how to do that is answered in the link I gave. – Bert Aug 20 '16 at 07:05

1 Answers1

0

Basically your methods must do : "return $this;" once treatment is done :

public function upload(){
    //do something

    return $this;
}

public function resize(){
    //do something

    return $this;
}

public function watermark(){
    //do something

    return $this;
}
vincenth
  • 1,732
  • 5
  • 19
  • 27
  • what if i have to only upload file and return the filename then I can't return object of the class. – Zartash Zulfiqar Aug 20 '16 at 10:24
  • You can do your whole treatment chaining methods, then call a getFileName method once you are done. – vincenth Aug 20 '16 at 10:27
  • But in laravel we didn't need to call any function for getting file name. I already think about it and whole logic is in my mind. But the issue is how framework manages this. – Zartash Zulfiqar Aug 20 '16 at 10:31