代码之家  ›  专栏  ›  技术社区  ›  online Thomas

如何重写包中的单个函数,以便与laravel一起内部使用?

  •  1
  • online Thomas  · 技术社区  · 8 年前

    我想重写中的函数 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);
        }
    }
    

    1 回复  |  直到 8 年前
        1
  •  2
  •   Phil Cross    8 年前

    创建名为的新服务提供程序 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']);
        });
    }
    

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

    然后,打开 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']);
            });
        }
    }
    

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

    在重写的方法中,指定应使用编译器而不是原始编译器。

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