Laravel 包读取包配置文件和未发布的配置文件

AdR*_*ock 4 php config packages laravel

我创建了一个 Laravel 包,将它上传到 packagist 并设法使用 composer require 安装它。

我现在遇到了一个问题,我不知道如何解决它,搜索也无济于事。

我有一个配置文件,它将默认配置文件发布到 config 目录。我对已发布的文件进行了更改,现在我希望我的包使用此配置文件,但它使用的是包中的配置文件,而不是新更新的发布文件。这是我在 vendor src 文件夹中的服务提供者

namespace Clystnet\Vtiger;

use Illuminate\Support\ServiceProvider;

class VtigerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/Config/config.php' => config_path('vtiger.php'),
        ], 'vtiger');

        // use the vendor configuration file as fallback
        $this->mergeConfigFrom(
            __DIR__ . '/Config/config.php', 'vtiger'
        );
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('clystnet-vtiger', function () {
            return new Vtiger();
        });

        config([
            'config/vtiger.php',
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要包类

<?php 
namespace Clystnet\Vtiger;

use Storage;
use Illuminate\Support\Facades\Config;

class Vtiger
{
    protected $url;
    protected $username;
    protected $accesskey;

    public function __construct() {
        // set the API url and username
        $this->url = Config::get('vtiger.url');
        $this->username = Config::get('vtiger.username');
        $this->accesskey = Config::get('vtiger.accesskey');
    }
   ...
Run Code Online (Sandbox Code Playgroud)

在我的课堂上,我正在做一个var_dump($this->url),但它没有读取正确的配置文件。

我如何设置它以使用正确的?

更新

这是我的自定义配置文件,也是包正在读取的文件

return [
    'url' => 'path/to/vtiger/webservice',
    'username' => '',
    'accesskey' => '',
];
Run Code Online (Sandbox Code Playgroud)

Man*_*eph 7

我遇到了同样的问题(联系人:是我的包裹)

VIMP:指定package_name.php作为您的配置文件名(例如:contact.php

第 1 步:首先,将您的“ mergeConfigFrom() ”方法移动到“ register() ”方法

public function register()
{
    $this->mergeConfigFrom(
        __DIR__.'/config/contact.php','contact'
    );
}
Run Code Online (Sandbox Code Playgroud)

第 2 步:从 config 文件夹中删除您发布的配置文件

第 3 步:使用 vendor:publish 再次发布

php artisan vendor:publish
Run Code Online (Sandbox Code Playgroud)

第 4 步:清除缓存

php artisan cache:clear

php artisan config:clear
Run Code Online (Sandbox Code Playgroud)

第 5 步:现在您可以访问您的配置值

$value = config('contact.default.send_email_to');
Run Code Online (Sandbox Code Playgroud)

第 6 步:我的配置文件是

<?php
    return [
        "default"=>[
            "send_email_to" => "mj@abc.com"
        ]
    ];
Run Code Online (Sandbox Code Playgroud)


Tro*_*yer 4

正如文档所说,您应该将其放在 register() 方法中,例如:

public function register()
{

  // use the vendor configuration file as fallback
  $this->mergeConfigFrom(
      __DIR__ . '/Config/config.php', 'vtiger'
  );

  ...

}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。

顺便说一句,你需要关心多维数组,因为文档说:

此方法仅合并配置数组的第一层。如果您的用户部分定义了多维配置数组,则缺少的选项将不会被合并。