laravel Facade provider 如何把自己的类或者第三方的类打造成facade样式

下面是偷别人的代码。

基本原理就是把各种类实例化后,放到一个数组里,然后使用到的时候,从这个数组里拿到对应的类处理程序。

下面是偷人家的代码:

SmartLogger.php

namespace AppSmartLogger;
class SmartLogger {
public function log($text) {
$path = storage_path('logs');
$myfile = fopen("{$path}/SmartLog.txt", "a");
fwrite($myfile, $text);
fwrite($myfile, PHP_EOL);
fclose($myfile);
}
}

SmartLoggerFacade.php

namespace AppSmartLogger;
use IlluminateSupportFacadesFacade;
class SmartLoggerFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'smartlogger';
}
}

SmartLoggerServiceProvider.php

namespace AppProviders;
use AppSmartLoggerSmartLogger;
use IlluminateSupportServiceProvider;
class SmartLoggerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->bind('smartlogger',function(){
return new SmartLogger();
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
} 

打开文件 configapp.php 找到 providers 数组,添加刚创建的类;

AppProvidersSmartLoggerServiceProvider::class

在 aliaes 数组中创建别名

'Smartlogger' => AppSmartLoggerSmartLoggerFacade::class

可以对刚创建的 facades 类进行测试了

这里调用的方法,无认是静态,动态的都可以用::来调用

use AppSmartLoggerSmartLoggerFacade as SmartLogger;




SmartLogger::log("Hi");  
原文地址:https://www.cnblogs.com/bfyang5130/p/14067841.html