Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

php - How to replace the Laravel Builder class

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?

This is what I have tried:

my Builder:

    use IlluminateDatabaseEloquentBuilder as BaseBuilder;
    class Builder  extends  BaseBuilder
    {

        /**
         * Find a model by its primary key.
         *
         * @param  mixed  $id
         * @param  array  $columns
         * @return IlluminateDatabaseEloquentModel|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;
        }
    }

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IlluminateDatabaseEloquentBuilder class is an internal class and as such it is not dependency injected into the IlluminateDatabaseEloquentModel class, but kind of hard coded there.

To do what you want to do, I would extend the IlluminateDatabaseEloquentModel to MyNamespaceDatabaseEloquentModel class and override newEloquentBuilder function.

public function newEloquentBuilder($query)
{
   return new MyNamespaceDatabaseEloquentBuilder($query);
}

Then alias MyNamespaceDatabaseEloquentModel to Eloquent at the aliases in app/config/app.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...