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 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度