Php 为什么要在laravel中创建facade而不是直接调用方法?
我只是从拉威尔开始,想了解这一点Php 为什么要在laravel中创建facade而不是直接调用方法?,php,laravel,dependency-injection,laravel-5,laravel-facade,Php,Laravel,Dependency Injection,Laravel 5,Laravel Facade,我只是从拉威尔开始,想了解这一点 //access session directly from the Service Container $value = $app->make('session')->get('key'); 假设我们的应用程序中有一个类: namespace App\Tests; class MyTest{ public function sayHello($name){ echo "Hello, $name!"; }
//access session directly from the Service Container
$value = $app->make('session')->get('key');
假设我们的应用程序中有一个类:
namespace App\Tests;
class MyTest{
public function sayHello($name){
echo "Hello, $name!";
}
public static function anotherTest(){
echo "another test...";
}
}
//access session directly from the Service Container
$value = $app->make('session')->get('key');
创建一个门面和一个服务提供者比仅仅使用它作为服务有什么好处
use App\Tests\MyTest;
//... controller declarations here ....
public function someaction(){
$mt = new MyTest();
$mt->sayHello('John');
//or
MyTest::anotherTest();
}
//... etc...
//access session directly from the Service Container
$value = $app->make('session')->get('key');
in-Laravel是从中获取对象并对其调用方法的唯一方便方法
//access session directly from the Service Container
$value = $app->make('session')->get('key');
因此,将正面称为:
//access session using a Facade
$value = Session::get('key');
//access session directly from the Service Container
$value = $app->make('session')->get('key');
就像做:
//access session directly from the Service Container
$value = $app->make('session')->get('key');
当Facade解析服务容器中的会话
键并在其上调用方法get
//access session directly from the Service Container
$value = $app->make('session')->get('key');
一旦了解了Facade的功能,您就应该了解什么是服务容器以及使用它的好处
//access session directly from the Service Container
$value = $app->make('session')->get('key');
Laravel云中的服务容器可以是依赖项注入容器和应用程序的注册表
//access session directly from the Service Container
$value = $app->make('session')->get('key');
与手动创建对象相比,使用服务容器的优势已在我的一篇文章和页面中说明,但简要介绍如下:
//access session directly from the Service Container
$value = $app->make('session')->get('key');
- 管理对象实例上的类依赖关系的能力
- 将接口绑定到具体类,以便在程序中请求接口时,服务容器会自动实例化具体类。更改绑定上的具体类将更改通过所有应用程序实例化的具体对象
- 创建单个入口并稍后将其取回的可能性(Singleton)