本文介绍了如何替换Laravel Builder类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用自己扩展的Laravels构建器类替换它.我认为这和App::bind一样简单,但似乎不起作用.我应该在哪里放置绑定,在Laravel中执行绑定的正确方法是什么?

I want to replace the Laravels builder class with my own that's extending from it. I thought it would be as simple as matter of App::bind but it seems that does not work. Where should I place the binding and what is the proper way to do that in Laravel?

这是我尝试过的:

我的生成器:

    use Illuminate\Database\Eloquent\Builder as BaseBuilder;
    class Builder  extends  BaseBuilder
    {

        /**
         * Find a model by its primary key.
         *
         * @param  mixed  $id
         * @param  array  $columns
         * @return \Illuminate\Database\Eloquent\Model|static|null
         */
        public function find($id, $columns = array('*'))
        {
            Event::fire('before.find', array($this));
            $result = parent::find($id, $columns);
            Event::fire('after.find', array($this));
            return $result;
        }
    }

接下来,我尝试将绑定注册到bootstrap/start.php文件中,如下所示:

And next I tried to register the binding in bootstrap/start.php file like this :

$app->bind('Illuminate\\Database\\Eloquent\\Builder', 'MyNameSpace\\Database\\Eloquent\\Builder');
return $app;

推荐答案

Illuminate\Database\Eloquent\Builder类是内部类,因此它不是依赖项注入到Illuminate\Database\Eloquent\Model类中,而是在其中进行了硬编码.

Illuminate\Database\Eloquent\Builder class is an internal class and as such it is not dependency injected into the Illuminate\Database\Eloquent\Model class, but kind of hard coded there.

要做你想做的事,我将Illuminate\Database\Eloquent\Model扩展到MyNamespace\Database\Eloquent\Model类并覆盖newEloquentBuilder函数.

To do what you want to do, I would extend the Illuminate\Database\Eloquent\Model to MyNamespace\Database\Eloquent\Model class and override newEloquentBuilder function.

public function newEloquentBuilder($query)
{
   return new MyNamespace\Database\Eloquent\Builder($query);
}

然后在app/config/app.phpaliases处将别名MyNamespace\Database\Eloquent\Model更改为Eloquent

Then alias MyNamespace\Database\Eloquent\Model to Eloquent at the aliases in app/config/app.php

这篇关于如何替换Laravel Builder类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:27