3

I have seen in Laravel calling multiple method in the single line, example:

DB::get('test')->toJson();

I have a cool class and view method in that class.

$this->call->view('welcome')->anotherMethod();

I would like to call another method also? Where should I make that method?

Fudge
  • 49
  • 4
user3501409
  • 43
  • 2
  • 6
  • 1
    in the class (if the previous methud return $this) on in whichever class the previous method returns (return $classIstance) – Damien Pirsy Jul 23 '15 at 10:50

1 Answers1

9

DB::get() seems to be a method returning an object, where you can call other functions (I think a result object of a database query). If you want to call multiple functions on one object in one line, you have to return $this in your functions, e.g.:

class View {
    public static function factory {
        // The question is: How useful is this factory function. In fact: useless in
        // the current state, but it can be extended in any way
        return new self;
    }

    public function one() {
        // do something
        return $this;
    }

    public function two() {
        // do something
        return $this;
    }
}

Then you can do:

$class = new View();
$class->one()->two();
// it's also possible to use the `factory` function
// you should think about, how useful this approach is in your application
$class = View::factory()->one()->two();

That's how you can do it in php, if laravel has some helpers for that, i can't say :)

Florian
  • 2,796
  • 1
  • 15
  • 25
  • let me try this if its work i will accept the answer .. but cant it possible without making object .. cant we do this like that viiew::one()->two() ? – user3501409 Jul 24 '15 at 05:15
  • 1
    If the static method `one()` of class `view` returns an object of view, yes, why not? Let me update the code to reflect such a factory method. But you should think about, how useful it is :) – Florian Jul 24 '15 at 05:18