How to use LaravelFacades?

Source: Internet
Author: User
Tags autoload autoloader silex
How to use LaravelFacades? Facade layout is a software design layout that is often used in object-oriented programming. Facade is actually a class that includes complex function libraries and provides more concise and easy-to-read interfaces. The Facade layout can also provide unified and well-designed APIs for a group of APIs with complex structures and simple designs.

The Laravel framework is similar to the layout, also known as Facades. In this tutorial, we will learn how to apply "Facades" of Laravel to other frameworks ". Before continuing, let's take a look at the Ioc container.

First, we understand the internal working structure of facades in Laravel. Then we will discuss how to transform it and use it in other environments.

Facades in Laravel

Laravel facade is a class that provides similar static interfaces for internal services of containers. According to the description in this document, Facades is a proxy that can touch the underlying implementation mode of container service.

However, in the PHP community, there has been a constant debate over their names. Some people insist on modifying this name to avoid developers' confusion because it does not fully implement the Facade layout. If you are also troubled by this name, you can take it as an alias. However, note that the Laravel framework base class (base class) that will be used below will be called Facade.

How Facades Are implemented in Laravel Facades

You may also know that each service in the container has a unique name. In laravel applications, you can use the App: make () method or app () helper function to directly obtain services from the container.

 methodName();

As mentioned above, Laravel's advantage of using the facade class is to make it easier for developers to use services. After using the facade class, the following code can achieve the same effect:

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

In Laravel, all services contain a facade class. These facade classes inherit from the Facade base class in the Illuminate/Support package. They only need to implement the getFacadeAccessor method, and the latter will return the service name in the container.

In the preceding example, someService represents the facade class. MethodName is actually a method of the original service in the container. If the preceding example is displayed in the Laravel context, a class named someService leads to a static method named methodName. But Laravel does not implement the interface in this way. In the next section, we will introduce how Laravel's Facade base class works behind the scenes.

Base Facade

The Facade class contains a private attribute named $ app whose value is a reference of the service container. To use facades outside Laravel, the container must explicitly use the setFacadeApplication () method.

Inside the facade base class, the _ callStatic magic method is used to call non-existing static methods. If you call the static method of the Laravel facade class, the _ callStatic method is activated because the facade class does not implement this method. Therefore, __callstatic obtains the respective services from the container and calls them.

The following describes how to implement the _ callStatic method in the facade base class:

 $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 preceding method, getFacadeRoot () gets the service from the container.

Facade class parsing

Each facade class inherits from the base class. We only need to implement the getFacadeAccessor () method, which is used to return the service name in the container.

 Alias

Since Laravel facades is a PHP class, we need to import them before use. PHP supports namespaces and automatic import. Therefore, you only need to call a fully qualified name to automatically load these classes. PHP also supports the use command to get aliases for classes:

use App\Facades\SomeServiceFacadeSomeServiceFacade:SomeMethod();

However, when a specific facade class is required, we must write the above code in each script file. Laravel has a unique method to process the facade alias-the alias loader (alias loader ).

How does Laravel add aliases to Facades?

All aliases are saved in the aliases array of the app. php configuration file, which is saved in the/config directory.

View the array and you will find that each alias corresponds to a fully qualified class name. This means we can select the facade classAnyName.

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

Now, let's see how Laravel uses this array to get aliases for the facade class. In the pilot phase, Laravel uses the AliasLoader service from the Illuminate \ Foundation package. AliasLoader uses this alias array as a parameter to traverse all its elements and uses PHP's spl_autoload_register to create a _ autoload function queue. Each _ autoload function uses the PHP class_alias function to create aliases for each facade class.

Therefore, we do not need to import and create aliases for classes before using the use command. When we try to use a non-existent class, PHP will check the _ autoload queue to obtain the appropriate autoloader. At this time, AliasLoader has noted down all the _ autoload functions. Each autoloader selects a class name and exports the corresponding initial class name based on the alias array. At last, it creates an alias for it. Refer to the following method call:

     

In the background, FancyName corresponds to App \ Facades \ SomeServiceFacade.

Use Facades in other frameworks

Now we know how Laravel handles facades and aliases. we can apply the facade method of Laravel to other environments. Next, we will use facades in the Silex framework. However, as long as you follow the same idea, you can use it in other frameworks.

Silex has containers inherited from Pimple. Use the $ app object to call services in the container:

   someMethod()

With the facade class, we can provide a static-like interface for the Silex service. In addition, we can also use the AliasLoader service to create meaningful aliases for these facades. Therefore, we can reorganize the above code:

   Prerequisites

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

Composer require illuminate \ support

This package also contains other services. Currently, we only need the facade base class.

Create Facades

You only need to inherit the Facade base class and implement the getFacadeAccessor method to create a facade for the service.

In this article, all facades will be saved in the src/Facades path. For example, for a service named some. service, its facade class is as follows:

       

Note that this class is located under the app \ facades namespace.

Currently, only application containers with the facade class are left. As mentioned above, calling a method of the facade class in a static context triggers the _ callStatic method. This method uses the data returned by getFacadeAccessor () to identify the services in the container and try to obtain them. When the facade base class is used outside Laravel, the container object is not set automatically and needs to be set manually.

To this end, you can set the application container of the facade class by using the setFacadeApplication method of the facade base class.

In the app. php file, add the following code:

        

This sets the container for all facades inherited from the facade base class.

Now, you do not need to directly obtain services from the container. we can use the created facade class to obtain services. This class also allows us to call all methods in the static context.

Implement alias

To create an alias for the facade class, we will use the AliasLoader we have previously introduced. The AliasLoader class is provided by the illuminate \ foundation package. you can download the entire package or copy part of the code to keep it as a file.

If you want to copy the source file, we recommend that you save it in the src/Facades directory. You can create a namespace for the AliasLoader class based on the project structure.

In this example, we copy the code and save it in the app/facades namespace.

Create an alias array

Create the aliases. php file in the config directory and enter alias-facade to bind:

       'App\Facades\SomeService',];

FancyName is the alias we created for App \ Facades \ SomeService.

Register an alias

AliasLoader is a singleton service. To create or obtain an instance of the alias loader, call the getInstance method and take the alias array as a parameter. Finally, to register these aliases, you need to call the register method.

Open the app. php file again and add the following code:

      register();

Now, we're done! We can use this service as follows:

      For packaging

A Facade class only needs to implement the getFacadeAccessor method, and the latter will return the service name in the container. To use facade outside the Laravel environment, you must use the setFacadeApplication () method to explicitly set the service container.

To reference the facade class, we can use the fully qualified class name or use the PHP use command to import it. Alternatively, follow Laravel's method of creating aliases for facades and use alias loader.

Http://www.sitepoint.com/how-laravel-facades-work-and-how-to-use-them-elsewhere/ (author: Reza Lavaryan) This article is compiled by OneAPM engineers.

OneAPM for PHP can go deep into all PHP applications to complete application performance management. it can go deep into all PHP applications to complete application performance management and monitoring, including visibility of code-level performance problems, fast identification and tracing of performance bottlenecks, Real User Experience Monitoring, server monitoring, and end-to-end application performance management. For more technical articles, visit the OneAPM official technical blog.

This article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.