2 回答

TA貢獻1831條經驗 獲得超4個贊

TA貢獻1813條經驗 獲得超2個贊
我不會詳細介紹,但這是對在 laravel 中使用外觀時幕后發生的事情的簡單解釋。
假設您使用一些公共方法定義了一個自定義類:
namespace Test;
class Foo
{
public function test()
{
return 'test';
}
}
然后你必須為這個類定義一個外觀:
namespace Test1;
class BarFacade
{
// In laravel this is called in the Facade abstract class but it is actually implemented
// by all the facades you add across the application
public static function getFacadeAccessor()
{
// In laravel you can also return a string which means that the object
// will be retrieved from the container.
return new \Test\Foo();
}
// In laravel this method is defined in the Facade abstract class
public static function __callStatic($method, $args)
{
$object = self::getFacadeAccessor();
return call_user_func_array([$object, $method], $args);
}
}
$aliases然后,您必須在文件的數組中定義別名config.app。這些別名由 laravel 解析并使用 php 內置函數class_alias 注冊(參見 Illuminate/Foundation/AliasLoader.php)
class_alias('Test\Foo', 'BarFacade', true);
// You can also create an alias for the facade itself
class_alias('Test1\BarFacade', 'FooBar', true);
然后你可以簡單地調用門面:\
var_dump(BarFacade::test());
var_dump(\Test1\BarFacade::test());
var_dump(\FooBar::test());
結果顯然是:
string(4) "test"
string(4) "test"
string(4) "test"
- 2 回答
- 0 關注
- 117 瀏覽
添加回答
舉報