• 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");  
  • 相关阅读:
    node
    github
    [模块] pdf转图片-pdf2image
    python 15 自定义模块 随机数 时间模块
    python 14 装饰器
    python 13 内置函数II 匿名函数 闭包
    python 12 生成器 列表推导式 内置函数I
    python 11 函数名 迭代器
    python 10 形参角度 名称空间 加载顺序
    python 09 函数参数初识
  • 原文地址:https://www.cnblogs.com/bfyang5130/p/14067841.html
Copyright © 2020-2023  润新知