How Laravel Facades Work and How to Use Them Elsewhere

View: 828    Dowload: 0   Comment: 0   Post by: daii   Category: Php&mySql   Fields: none

The Facade pattern is a software design pattern which is often used in object oriented programming. A facade is, in fact, a class wrapping a complex library to provide a simpler and more readable interface to it. The Facade pattern can also be used to provide a unified and well-designed API to a group of complex and poorly designed APIs.

 

The Laravel framework has a feature similar to this pattern, also termed Facades. In this tutorial we will learn how to bring Laravel’s “Facades” to other frameworks. Before we continue, you need to have a basic understanding of Ioc containers.

Let’s first go through the inner working parts of Laravel’s facades, and then we’ll discuss how we can adapt this feature to the other environments.

Facades in Laravel

A Laravel facade is a class which provides a static-like interface to services inside the container. These facades, according to the documentation, serve as a proxy for accessing the underlying implementation of the container’s services.

There have been many debates in the PHP community about this naming, though. Some have argued that the term should be changed in order to avoid confusion of developers, as it doesn’t fully implement the Facade pattern. If this naming confuses you, feel free to call it whatever feels right to you, but please note that the base class that we’re going to use is called Facade in the Laravel framework.

How Facades Are implemented in Laravel

As you probably know, every service inside the container has a unique name. In a Laravel application, to access a service directly from the container, we can use the App::make() method or the app() helper function.

<?php

App::make('some_service')->methodName();

As mentioned earlier, Laravel uses facade classes to make services available to the developer in a more readable way. By using a facade class, we would only need to write the following code to do the same thing:

// ...
someService::methodName();
// ...

In Laravel, all services have a facade class. These facade classes extend the base Facade class which is part of the Illuminate/Support package. The only thing that they need to implement is the getFacadeAccessor method, which returns the service name inside the container.

In the above syntax, someService refers to the facade class. The methodName is in fact a method of the original service in the container. If we look at this syntax outside of the context of Laravel, it would mean that there’s a class named someService exposing a static method named methodName(), but that’s not how Laravel implements this interface. In the next section, we’ll see how Laravel’s base Facade class works behind the scenes.

Base Facade

The Facade class has a private property named $app which stores a reference to the service container. If we need to use facades outside of Laravel, we have to explicitly set the container using setFacadeApplication() method. We’ll get to that shortly.

Inside the base facade class, the __callStatic magic method has been implemented to handle calling of static methods which don’t actually exist. When we call a static method against a Laravel facade class, the __callStatic method is invoked, because the facade class hasn’t implemented that method. Consequently, __callStatic fetches the respective service from the container and calls the method against it.

Here is the implementation of the __callStatic method in the base facade class:

<?php
// ...
/**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        switch (count($args)) {
            case 0:
                return $instance->$method();

            case 1:
                return $instance->$method($args[0]);

            case 2:
                return $instance->$method($args[0], $args[1]);

            case 3:
                return $instance->$method($args[0], $args[1], $args[2]);

            case 4:
                return $instance->$method($args[0], $args[1], $args[2], $args[3]);

            default:
                return call_user_func_array([$instance, $method], $args);
        }
    }

In the above method, getFacadeRoot() gets the service from the container.

Anatomy of a Facade Class

Each facade class extends the base class. The only thing that we need to implement is the getFacadeAccessor() method. This method does nothing but return the service’s name in the container.

<?php namespace App\Facades;

use Illuminate\Support\Facades\Facade as BaseFacade;

class SomeServiceFacade extends BaseFacade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'some.service'; }

}

Aliases

Since Laravel facades are PHP classes, we need to import them before we can use them. Thanks to the namespaces and autoloading support in PHP, all classes are automatically loaded when we access them by the fully-qualified name. PHP also supports aliasing of classes by using the use directive:

use App\Facades\SomeServiceFacade

SomeServiceFacade:SomeMethod();

However, we have to do this in each and every script where we need that particular facade class. Laravel handles the aliasing of facades in its own way by using an alias loader.

How Laravel Aliases the Facades

All alias names are kept in an aliases array inside the app.php config file, which is located inside the /config directory.

If we take a look at the array, we can see that each alias name is mapped to a fully-qualified class name. This means we can use any name that we wish for a facade class:

// ..
'aliases' => [
    // ...
    'FancyName' => 'App\Facades\SomeServiceFacade',
],

Okay, now let’s see how Laravel uses this array for aliasing the facade classes. In the bootstrapping phase, Laravel uses a service named AliasLoader which is part of the Illuminate\Foundation package. AliasLoader takes the aliases array, iterates over all the elements, and creates a queue of __autoload functions using PHP’s spl_autoload_register. Each __autoload function is responsible for creating an alias for the respective facade class by using PHP’s class_alias function.

As a result, we won’t have to import and alias the classes before using them as we normally do with the use directive. So whenever we try to access a class that doesn’t exist, PHP will check the __autoload queue to get the proper autoloader. By that time, AliasLoader has already registered all the __autoload functions. Each autoloader takes a fancy class name and resolves it to the original class name according to the aliases array. Finally, it creates an alias for that class. Consider the following method call:

<?php

// FancyName is resolved to App\Facades\SomeServiceFacade according to the aliases array

FancyName::someMethod()

Behind the scenes, FancyName is resolved to App\Facades\SomeServiceFacade.

Using Facades in Other Frameworks

Okay, now that we have a good understanding of the way Laravel handles its facades and aliases, we can adapt Laravel’s facade approach to other environments. In this article, we’re going to use facades in the Silex framework. However, you can adapt this feature to other frameworks as well by following the same concept.

Silex has its own container, as it extends Pimple. To access a service inside the container, we can use the $app object like so:

<?php
$app['some.service']->someMethod()

With the help of facade classes, we can provide a static-like interface to our Silex services as well. In addition to that, we can use the AliasLoader service to make meaningful aliases for those facades. As a result, we would be able to refactor the above code like so:

<?php
SomeService::someMethod();

Requirements

To use the the base facade class, we need to install the Illuminate\Support package using composer:

composer require illuminate\support

This package contains other services as well, but for now we just need its base Facade class.

Creating the Facades

To create a facade for a service, we just need to extend the base Facade class and implement the getFacadeAccessor method.

For this tutorial, let’s keep all the facades under src/Facades path. As an example, for a service named some.service, the facade class would be as follows:

<?php
namespace App\Facades

use Illuminate\Support\Facades\Facade;

class SomeServiceFacade extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'some.service'; }

}

Please note that we have namespaced the class under app\facades.

The only thing that remains is setting the application container on the facade class. As pointed out earlier, when we call a method in a static context against a facade class, __callStatic is triggered. _callStatic uses data returned by getFacadeAccessor() to identify the service inside the container and tries to fetch it. When we’re using the base Facade class outside of Laravel, the container object isn’t set automatically, so we will need to do this manually.

To do this, the base facade class exposes a method named setFacadeApplication which sets the application container for that facade class.

In our app.php file, we need to add the following code:

<?php
Illumiante\Support\Facade::setFacadeApplication($app);

This will set the container for all the facades which are extending the base facade class.

Now, instead of accessing the service from our container, we can use the facade class we just created, also allowing us to call all methods in a static context.

Implementing the Aliases

To alias the facade classes, we’re going to use the AliasLoader that we introduced earlier. Aliasloader is part of the illuminate\foundation package. We can either download the whole package or just borrow the code and keep it as a file.

If you just want to copy the source file, I suggest you keep it under src/Facades. You can namespace the AliasLoader class based on your project’s architecture.

For this example, let’s copy the code and namespace it under app/facades.

Creating the Aliases Array

Let’s create a file in our config directory called aliases.php and put the alias-facade bindings in there like so:

<?php
return [
    'FancyName' => 'App\Facades\SomeService',
];

FancyName is a name that we want to use instead of App\Facades\SomeService.

Registering the Aliases

AliasLoader is a singleton service. To create or get the alias loader’s instance, we need to call the getInstance method with the array of aliases as an argument. Finally, to register all the aliases, we need to call its register method.

Again in the app.php file, add the following code:

<?php

// ...

$aliases = require __DIR__ . '/../../config/aliases.php';
App\Facades\AliasLoader::getInstance($aliases)->register();

And that’s all there is to it! Now we can use the service like so:

<?php
FancyName::methodName();

How Laravel Facades Work and How to Use Them Elsewhere

The Facade pattern is a software design pattern which is often used in object oriented programming. A facade is, in fact, a class wrapping a complex library to provide a simpler and more readable interface to it. The Facade pattern can also be used to provide a unified and well-designed API to a group of complex and poorly designed APIs.

Posted on 20-11-2015 

Comment:

To comment you must be logged in members.

Files with category

  • SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    View: 337    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout. SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays...

  • How to use the PHP download file script? Class Download PHP

    How to use the PHP download file script? Class Download PHP

    View: 215    Download: 2   Comment: 0

    Category: Php&mySql     Fields: Other

    This is my favorite PHP download script. I’ve used a different more simple method until a client wanted to be able to allow their site visitors to download a large file from a password protected directory. The PHP script works on Apache web servers...

  • Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    View: 359    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    You’ll need to stop Apache (web server) using the following command. In any Linux commands I show in this article, it presumes you aren’t logged in as the root user, so you will need to use sudo to issue privileged commands.

  • PHP source code: get content of google search

    PHP source code: get content of google search

    View: 281    Download: 2   Comment: 0

    Category: Php&mySql     Fields: Other

    How to get the results of google search and display on your website. This PHP code can do that. Refer to the following code.

  • PHP as a Scripting Language for C#

    PHP as a Scripting Language for C#

    View: 227    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    When creating .NET applications (including desktop and web applications), it may be useful to allow extending the application using some scripting language. The users of the application can write simple scripts to configure the application, modify...

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 4306    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    How to MySqli Tutorial PHP MySqli Extension

    View: 623    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    Make Laravel Artisan Commands

    View: 592    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

 
File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd