我有自己的函数存储在相对于 helpers.php
文件的 helpers
文件夹中的 composer.json
文件中。
<?php
function config (string $params){}
function redirect() {}
在文件 composer.json
中,此文件包含在 autoload
"autoload": {
"psr-4": {
"App\\" : "./app"
},
"files": [
"helpers/helpers.php"
],
"scripts": {
"delete-all-tables": "App\\Migrations\\DeleteTable::deleteAllTables",
}
}
我在连接 composer-dump
后使用了 helpers
。
我在此位置使用 config ()
:
<?php
namespace App\Migrations;
use App\Components\Migration;
class DeleteTable extends Migration
{
public static function deleteAllTables()
{
$param = config('db.dbname');
$instance = new self();
$instance->con->query("DROP DATABASE " . $param . "; CREATE DATABASE " . $param . "; USE " . $param . ";");
}
}
在 Migration
类中使用我的函数而不是通过 Composer 时,一切正常,但是当通过 scripts
调用 Terminal
命令时,config
函数不会执行.然后出现错误:
Fatal error: Uncaught Error: Call to undefined function App\Migrations\config() in D:\OSPanel\domains\myshop\app\Migrations\DeleteTable.php:17
Stack trace:
#0 phar://C:/composer/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php(324): App\Migrations\DeleteTable::deleteAllTables(Object(Composer\Script\Event))
#1 phar://C:/composer/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php(218): Composer\EventDispatcher\EventDispatcher->executeEventPhpScript('App\\Migrations\\...', 'dele
teAllTables', Object(Composer\Script\Event))
#2 phar://C:/composer/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php(101): Composer\EventDispatcher\EventDispatcher->doDispatch(Object(Composer\Script\Event))
#3 phar://C:/composer/composer.phar/src/Composer/Command/ScriptAliasCommand.php(64): Composer\EventDispatcher\EventDispatcher->dispatchScript('delete-all-tabl...', true, Array)
#4 phar://C:/composer/composer.phar/vendor/symfony/console/Command/Command.php(245): Composer\Command\ScriptAliasCommand->execute(Obje in D:\OSPanel\domains\myshop\app\Migrations\Delet
eTable.php on line 11
你能告诉我我做错了什么吗?
有没有在课堂上不使用助手的情况下解决问题的选择? 非常感谢您的帮助!
答案 0 :(得分:0)
回调只能从 psr-0、psr-4 和 classmap 定义自动加载类。如果定义的回调依赖于在类之外定义的函数,则回调本身负责加载包含这些函数的文件。
因此通常作为 files
自动加载器类型的一部分包含的任何文件都不会包含在这种特定情况下。
在我看来,要解决这个问题,您有两个选择:
static
成员函数移动到辅助类中,并通过 Composer 自动加载机制(psr-0 或 psr-4)加载该类helpers.php
文件和 require
在迁移文件中的位置首先,它看起来像(在 app/Helpers.php
中):
<?php
namespace App;
class Helper {
static function config (string $params){}
static function redirect() {}
}
会被这样调用:
\App\Helpers::config('db.dbname');
第二,从 37925437 中汲取灵感,您的 DeleteTable.php
最终可能是这样的:
<?php
namespace App\Migrations;
use App\Components\Migration;
class DeleteTable extends Migration
{
public static function deleteAllTables()
{
require(dirname(\Composer\Factory::getComposerFile()) . '/helpers/helpers.php');
$param = config('db.dbname');
$instance = new self();
$instance->con->query("DROP DATABASE " . $param . "; CREATE DATABASE " . $param . "; USE " . $param . ";");
}
}