10

Laravel 的辅助函数有if ( ! function_exists('xx'))保护。

我可以指定 , 的顺序autoload_files并让Kint.class.phprequire 之前helpers.php吗?

return array( 
    $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
    $vendorDir . '/raveren/kint/Kint.class.php',
);
4

2 回答 2

3

这真是一个令人讨厌的问题。我为作曲家提交了功能请求:https ://github.com/composer/composer/issues/6768

应该有一种方法可以指定自动加载的操作顺序,以便可以在“require”或“require-dev”部分的任何类之前加载您的自定义“文件”;任何需要您在 vendor/ 内编辑 3rd 方包的解决方案充其量都是 hacky,但目前,我认为没有其他好的选择。

我能想到的最好的办法是使用脚本来修改 vendor/autoload.php 以便它在包含任何自动加载类之前强制包含您的文件。这是我的modify_autoload.php

<?php
/**
 * Updates the vendor/autoload.php so it manually includes any files specified in composer.json's files array.
 * See https://github.com/composer/composer/issues/6768
 */
$composer = json_decode(file_get_contents('composer.json'));

$files = (property_exists($composer, 'files')) ? $composer->files : [];

if (!$files) {
    print "No files specified -- nothing to do.\n";
    exit;
}

$patch_string = '';
foreach ($files as $f) {
    $patch_string .= "require_once __DIR__ . '/../{$f}';\n";
}
$patch_string .= "require_once __DIR__ . '/composer/autoload_real.php';";

// Read and re-write the vendor/autoload.php
$autoload = file_get_contents(__DIR__ . '/vendor/autoload.php');
$autoload = str_replace("require_once __DIR__ . '/composer/autoload_real.php';", $patch_string, $autoload);

file_put_contents(__DIR__ . '/vendor/autoload.php', $autoload);

您可以手动运行它,也可以通过将它添加到 composer.json 脚本让 composer 运行它:

{
 // ... 
  "scripts": {
    "post-autoload-dump": [
      "php modify_autoload.php"
    ]
  }
 // ...
}
于 2017-10-27T15:17:45.793 回答
2

我通过多种方式对此进行了测试,将我的助手也添加到自动加载中,并且仍然是我们首先加载的 Laravel 助手。

所以我的解决方案是在供应商自动加载之前包含您自己的辅助函数。

我在index.php文件public夹中的文件中做到了

//my extra line
require_once __DIR__.'/../app/helpers.php';

//this is laravel original code
//I make sure to include before this line

require __DIR__.'/../vendor/autoload.php';

在你的助手文件中,你可以定义你的助手函数:

 function camel_case($value)
 {
     return 'MY_OWN_CAMEL_CASE';
 }
于 2017-10-08T07:58:31.207 回答