Facades

A Facade is simply a service locater. Facades provide what appears to be static access to an instantiated service within the application container by converting static function calls to standard method calls via the php magic method __callStatic().

Definition:

  • the face of a building, esp. the principal front that looks onto a street or open space.
  • an outward appearance that is maintained to conceal a less pleasant or creditable reality.

This actually applies to software as well!

All of the core Disco services/classes have Facade access. This does not mean you have to work with them in such a manner, but man does it make for some clean swappable code.

3 Parts of a Facade #

// Step 1:
// The service the facade will be providing access to
class MyTestService {

    public $count = 1;

    public function test(){
        View::html("<p>Called test {$this->count++} times");
    }

}


// Step 2:
// The Facade class that extends the `Disco\classes\Facade` class
class TestFacade extends Disco\classes\Facade {

    protected static function returnFacadeId(){
        return 'TestFacade';
    }

}


// Step 3:
// Register the service in the container with the same key as returned from 
// the Facades method returnFacadeId()
App::make('TestFacade', 'MyTestService');



// Done!
// Now lets use the facade

TestFacade::test();
TestFacade::test();

// The views body will now contain 
// - <p>Called test 1 times</p>
// - <p>Called test 2 times</p>

Every Facade you create must implement the method protected static function returnFacadeId() and you should return a unique string key that specifies what key the facade accesses in the application container.

Get the Underlying Service Instance #

// If you want direct access to a Facades service from the container
// call the instance() method

$db = DB::instance();