laravel - 如何覆盖包中的单个函数以供 Laravel 内部使用?

标签 laravel package

我想重写 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);
    }
}

这不起作用

最佳答案

创建一个名为ViewServiceProvider的新服务提供者,然后在其中删除register和boot方法,并使其扩展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']);
    });
}

请注意,在单例方法中,我如何使用您的 Blade 编译器类。

然后,打开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 View 服务提供程序来实现的,因此所有现有方法都可以按预期工作。然后,您需要重写 registerBladeEngine() 方法,以便调用您重写的方法,而不是照亮提供程序中的方法。

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

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

关于laravel - 如何覆盖包中的单个函数以供 Laravel 内部使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607473/

相关文章:

mysql - 迁移处理不支持的类型

php - 在 Laravel 4 中创建管理员界面的最佳实践

Java错误包不存在

r - "How can I use R to extract only one channel from a multi-channel WAV file in order to enable soundecology to calculate indices?"

Java:Android类和api包层次继承

php - 我想在 laravel 中用 utf8 写一个文件来放置准确的数据

php - Laravel Raw SQL 查询命名参数绑定(bind)顺序

mysql - 用laravel上传图片并进行图片干预到本地路径

python - setup.py 中包含哪些包?

r - 从 Github 安装时,包中缺少整理字段中的文件