duan5801 2016-03-17 13:06
浏览 25
已采纳

为什么在laravel中创建一个外观而不是直接调用方法?

I'm just starting with laravel and want to understand this...

Lets say we have a class in our application:

namespace App\Tests;
class MyTest{

    public function sayHello($name){
        echo "Hello, $name!";
    }

    public static function anotherTest(){
        echo "another test...";
    }

}

What is the advantage of creating a facade and a service provider over just using it as

use App\Tests\MyTest;

//... controller declarations here ....

public function someaction(){

    $mt = new MyTest();
    $mt->sayHello('John');

    //or
    MyTest::anotherTest();

}

//... etc...
  • 写回答

1条回答 默认 最新

  • duan198409 2016-03-17 13:14
    关注

    A Facade in Laravel is only a convenient way to get an object from the Service Container and call a method on it.

    So calling a Facade like this :

    //access session using a Facade 
    $value = Session::get('key'); 
    

    Is like doing:

    //access session directly from the Service Container
    $value = $app->make('session')->get('key'); 
    

    As the Facade resolves the session key out of the Service Container and call the method get on it

    Once understood what a Facade does, you should understand what is the Service container and what are the benefits of using it

    The Service Container in Laravel cloud be a Dependency Injection Container and a Registry for the application

    The advantages of using a Service Container over creating manually your objects are stated in one of my previous answers and in the doc page, but briefly:

    • Capacity to manage class dependencies on object instantation
    • Binding of interfaces to concrete classes, so that when a interface is requested in your program, a concrete class is instantiated automatically by the service container. Changing the concrete class on the binding, will change the concrete objects instantiated through all your app
    • Possibility to create single intances and get them back later (Singleton)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算