【问题标题】:How to override a single function in a package for internal use with laravel?如何覆盖包中的单个函数以供 laravel 内部使用?
【发布时间】:2018-11-09 11:22:00
【问题描述】:

我想重写vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php中的一个函数

或者更确切地说是该文件使用的特征Illuminate\View\Compilers\Concerns\CompilesEchos.php 之外的函数。但是我找不到关于如何覆盖包的非常明确的信息。有人可以帮我理解一下。

我了解我需要扩展 BladeCompiler

我们称之为 MyBladeCompiler

class MyBladeCompiler extends BladeCompiler
{
    public function compileEchoDefaults($value)
    {
        return 'test';
        return preg_replace('/^(?=\$)(.+?)(?:\s+or\s+)(.+?)$/si', 'isset($1) ? $1 : $2', $value);
    }
}

我现在想将它注册为要使用的新类。我明白这应该在服务提供商中完成,但是如何?

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
      $this->app->bind(BladeCompiler::class, MyBladeCompiler ::class);
    }
}

这不起作用

【问题讨论】:

    标签: laravel package


    【解决方案1】:

    新建一个名为ViewServiceProvider的服务提供者,然后在其中删除注册和启动方法,并使其扩展Illuminate\View\ViewServiceProvider

    然后,添加这个方法:

    public function registerBladeEngine($resolver)
    {
        // The Compiler engine requires an instance of the CompilerInterface, which in
        // this case will be the Blade compiler, so we'll first create the compiler
        // instance to pass into the engine so it can compile the views properly.
        $this->app->singleton('blade.compiler', function () {
            return new MyBladeCompiler(
                $this->app['files'], $this->app['config']['view.compiled']
            );
        });
    
        $resolver->register('blade', function () {
            return new CompilerEngine($this->app['blade.compiler']);
        });
    }
    

    注意在单例方法中,我使用的是你的刀片编译器类。

    然后,打开config/app.php,将\Illuminate\View\BladeServiceProvider::class记录替换为自己的服务商。

    所以服务提供者应该是这样的:

    namespace App\Providers;
    
    use MyBladeCompiler
    use Illuminate\View\ViewServiceProvider as BaseViewServiceProvider;
    
    class ViewServiceProvider extends BaseViewServiceProvider
    {
        public function registerBladeEngine($resolver)
        {
            $this->app->singleton('blade.compiler', function () {
                return new MyBladeCompiler(
                    $this->app['files'], $this->app['config']['view.compiled']
                );
            });
    
            $resolver->register('blade', function () {
                return new CompilerEngine($this->app['blade.compiler']);
            });
        }
    }
    

    这通过扩展 Illuminate 视图服务提供程序来工作,因此所有现有方法都按预期工作。然后,您需要重写 registerBladeEngine() 方法,以便调用您重写的方法,而不是照明提供程序中的方法。

    在您被覆盖的方法中,您指定应该使用您的编译器而不是原始编译器。

    然后,您可以通过编辑 app.php 配置文件来指定使用您的扩展视图服务提供者而不是照明服务提供者。

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 2021-01-06
      • 2013-10-31
      • 2018-01-03
      • 2015-09-26
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多