Search code examples
phpooplaravelfluent-interface

Use Fluent Interface with less Code


How can I reduce these two lines

$foo = new Bar();
$baz = $foo->methodOne('param')->methodTwo('param');

to

$baz = Bar::methodOne('param')->methodTwo('param');

I´ve seen this specially in Laravel and it´s nice readable Code. But I stuck getting this to work with some custom Helper-Classes. It feels like mixing static + nonstatic functions which is confusing for now ...


Solution

  • For everyone passing by: Laravel offers a design pattern called Facades to achieve that effect. http://laravel.com/docs/5.1/facades

    If you want to build your own Helper-Class there are four things need:

    1. Helper Class itself
    2. Service Container binding of that class
    3. Facade Class "pointing" to Service Container
    4. Alias in app.php