How do I use Laravel facades?

Source: Internet
Author: User
Tags autoloader silex
Facade layout is a kind of software design layout which is used frequently in object-oriented programming. Facade is actually a class that includes a complex library of functions, providing a more concise and readable interface. The facade layout also provides a unified, well-designed API for a set of complex, poorly designed APIs.

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

First, we understand Laravel's facades internal work structure. Then we will discuss how to transform it and use it in other environments.

The facades in Laravel

Laravel facade is a class that provides a similar static interface to a container's internal service. According to its documentation, facades is an agent that touches the underlying implementation of the container service.

However, in the PHP community, the controversy over its name has been constant. Some people insist on modifying this name to avoid confusion for the developer because it does not fully implement the facade layout. If you are also troubled by this name, you can take an individual name for it. Note, however, that the Laravel framework base class, which will be used later, will be called facade.

How facades is implemented in Laravel

How facades is implemented in Laravel

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

 
  MethodName ();

As mentioned earlier, the benefit of using the facade class for Laravel is to make it easier for developers to use the service. With 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, which returns the service name within the container.

In the example above, Someservice represents the facade class. MethodName is actually a method of the original service within the container. If you look outside the Laravel context to see the example above, it means that a class named Someservice brings up a static method named MethodName (). However, Laravel does not implement the interface in this way. In the next section, we'll show you how Laravel's facade base class works behind the scenes.

Base facade

The facade class contains a private property named $app whose value is a reference to the service container. If you want to use facades outside of Laravel, you must make the container explicitly use the Setfacadeapplication () method.

Inside the facade base class, the __callstatic Magic method is used to handle calls to static methods that do not actually exist. If you call a static method of the Laravel facade class, the __callstatic method is activated because the facade class does not implement the method. As a result, __callstatic gets its own service from the container and then calls it.

The following is how the __callstatic method in the facade base class is implemented:

 
  $method ();            Case 1:                $method return $instance ($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 method above, 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 returns the service name in the container.

    

Alias

Since Laravel facades is a PHP class, we have to import them before using them. PHP supports namespaces and auto-import, so you can automatically load these classes whenever you call a fully qualified name. PHP also supports using the use directive to alias classes:

Use App\facades\someservicefacadesomeservicefacade:somemethod ();

However, when a particular facade class is needed, we have to write the above code over each script file. Laravel has a unique way of dealing with facade aliases-the alias loader (aliases loader).

Laravel How to add aliases to facades

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

Looking at the array, you will see that each alias corresponds to a fully qualified class name. This means that we can select any name for the facade class.

// ..' Aliases ' = [    //...    ' Fancyname ' = ' app\facades\someservicefacade ',],

Now let's take a look at how Laravel uses the array to alias the facade class. During the boot phase, Laravel will use the Aliasloader service from the Illuminate\foundation package. Aliasloader iterates through all its elements with the alias array as an argument, creating a __autoload function queue using PHP's spl_autoload_register. Each __autoload function creates aliases for each facade class using the PHP Class_alias function.

Therefore, we do not need to import and create aliases for a class before using it as you would with the use directive. When we try to use a nonexistent class, PHP checks the __autoload queue for proper autoloader. At this point, Aliasloader has written down all the __autoload functions. Each autoloader will select a class name and derive the corresponding initial class name based on the alias array. Finally, it creates an alias for it. Refer to the following method call:

     

Behind the scenes, Fancyname will correspond to App\facades\someservicefacade.

Using facades in other frameworks

Now that we have an idea of how Laravel handles facades and aliases, we can apply Laravel facade methods to other environments. Next, we'll use facades in the Silex framework. However, as long as you follow the same philosophy, you can also use it in other frameworks.

Silex has a container that inherits from Pimple. Use $app object to invoke services within the container:

 
    SomeMethod ()

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

      

Required conditions

To use the facade base class, we use the composer directive to install the Illuminate\support package:

Composer require Illuminate\support

This package also contains additional services. But for now we just need to facade the base class.

Create facades

You can create facade for a service simply by inheriting the facade base class and implementing the Getfacadeaccessor method.

In this article, all facades are saved under the Src/facades path. For example: A service named Some.service, whose facade class is as follows:

       

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

Now only the application container that sets the facade class is left. As mentioned earlier, the method of facade class is lowered in static context, and the __callstatic method is triggered. The method uses the data returned by the Getfacadeaccessor () to identify the service within the container and attempt to obtain it. When using the facade base class outside of Laravel, the container object is not automatically set and needs to be set manually.

To do this, use the Setfacadeapplication method of the facade base class to set the application container for the facade class.

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

        

This will set the container for all facades that inherit from the facade base class.

Now, without having to get the service directly from the container, we can get it using the facade class we just created, which also allows us to invoke all the methods in the static context.

Implementing aliases

In order to create aliases for the facade class, we will use the Aliasloader described earlier. The Aliasloader class is provided by the Illuminate\foundation package, can download the entire package, or copy some of the code to remain as a file.

If you want to copy the source file, it is recommended to save it in the Src/facades directory. You can create namespaces for the Aliasloader class based on the structure of your project.

In this example, we will copy the code and save it under the App/facades namespace.

Creating an array of aliases

Create the aliases.php file in the Config directory and fill in the Alias-facade bindings:

 
       ' App\facades\someservice ',];

Fancyname is the alias we created for App\facades\someservice.

Register aliases

Aliasloader is a single-instance service. To create or get an instance of the alias loader, call the GetInstance method and use the alias array as the parameter. Finally, in order to register these aliases, call its register method.

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

 
       Register ();

Now, it's done! We can use the service in this way:

!--? phpfancyname::methodname ();    

for Packaging

A facade class can only implement the Getfacadeaccessor method, which returns the service name within the container. To use facade outside of the Laravel environment, you must explicitly set the service container using the Setfacadeapplication () method.

To refer to the facade class, we can import it using fully qualified class names or using PHP's use directives. Or, follow the Laravel method for creating aliases for facades, using alias loader.

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

OneAPM for PHP is able to drill down into all of the PHP applications to perform application performance management in-depth application performance management and monitoring within all PHP applications, including the visibility of code-level capability issues, rapid identification and tracking of performance bottlenecks Real user experience monitoring, server monitoring, and end-to-end application performance management. To read more technical articles, please visit the OneAPM Official technology blog.

This article goes from OneAPM official blog

  • Related 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.