How to extend and modify a vendor model in Laravel

2019-05-11 23:50发布

I am working with a package antonioribeiro/firewall in my Laravel 5 application and I am using the database to store the list of IP addresses to be blocked.

I have installed it successfully and I am able to use the PragmaRX\Firewall\Vendor\Laravel\Models\Firewall model that it comes with too.

The problem that I have is that I am working with a multi tenant database where basically every tenant has their own database and the models for these tenants use the $connection property to specify the tenant connection and behind the scenes I change the tenant connection config accordingly to the request.

Now the model that comes with package looks like so:

<?php namespace PragmaRX\Firewall\Vendor\Laravel\Models;
/**
 * Part of the Firewall package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the 3-clause BSD License.
 *
 * This source file is subject to the 3-clause BSD License that is
 * bundled with this package in the LICENSE file.  It is also available at
 * the following URL: http://www.opensource.org/licenses/BSD-3-Clause
 *
 * @package    Firewall
 * @author     Antonio Carlos Ribeiro @ PragmaRX
 * @license    BSD License (3-clause)
 * @copyright  (c) 2013, PragmaRX
 * @link       http://pragmarx.com
 */

use Illuminate\Database\Eloquent\Model as Eloquent;

class Firewall extends Eloquent {

    protected $table = 'firewall';

    protected $guarded = array();

}

I added protected $connection = 'tenant'; to it to make it work but I am editing vendor files which won't show up in the version control. So being a novice developer I am trying to figure out how to extend this model somehow and then put the $connection property.

I tried creating a new model in the App namespace and extended the model that comes with the package but in vain.

So how do I extend the model that comes with the package to add to it so that it shows up in the version control and I am not editing vendor files?

1条回答
唯我独甜
2楼-- · 2019-05-12 00:30

Editing vendor files is a bad idea. If you for some reason HAVE to edit them, I would recommend forking the package and edit in the forked version, then update the composer file to pull the package from your own fork instead. But I would not recommend doing this in a case like this.

Instead you should publish the package config file and change the model that it should use.
This is done by using the artisan vendor:publish command in the terminal.
A new configuration file for the firewall package should be created in your config folder.
Then all you need to do is create your own model and change the firewall_model property in the config file:

https://github.com/antonioribeiro/firewall/blob/master/src/config/config.php

查看更多
登录 后发表回答