我的组件如下所示:
namespace App\View\Components;
use Illuminate\View\Component;
use App\Http\Controllers;
use Illuminate\Http\Request;
class shopImageContainer extends Component
{
public $image;
public $ph;
public $va;
public $config;
/**
* Create a new component instance.
*@param string $ph
*@param string $va
* @return void
*/
public function __construct($ph, $va, $image)
{
$this->image = $image;
$this->va = $va;
$this->ph = $ph;
$this->config = Controllers\GlobalFunctions::getConfig($ph, $va);
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\Contracts\View\View|string
*/
public function render()
{
return view('components.shop-image-container');
}
}
在我的 component.blade 中,我有这一行/ block 抛出错误“Undefined variable: config”:
@if($config->dd)
<div class="col bg-dark text-center p-3">
<a class="btn btn-primary rounded-0 " href="/download/{{ basename($image) }}" role="button">Download in {{ $config->ddLongEdge }}px</a>
</div>
@endif
似乎没有调用构造函数方法(我在方法中尝试了 dd("test) 并且没有输出) 有趣的是,它在我的本地环境中工作,但在服务器(apache2)上不工作 我在某处读到组件可能存在错误,服务器配置可能有问题,在这两种情况下都没有关于解决问题的更多详细信息。 感谢您的帮助
最佳答案
我搜索了一整天试图找到解决这个问题的方法。我的开发环境是 Mac,但我的服务器是 Ubuntu 环境。
您的文件名和类名似乎应该遵循 PSR-4自动加载标准。
这里你的 Controller 文件名和你的 Controller 名称应该是 PascalCase 并且区分大小写。
如果不遵循 PSR-4 标准,您的文件不会自动加载,这将触发此错误。由于在生成 View 时未调用构造方法。
我通过将所有 Controller 及其名称重命名为 PascalCase 并遵循 PSR-4 标准来解决这个问题。
这显然解决了我的问题。
你可以跑
Composer 更新
可能还有另一个命令,但这会更新您的包,并对不符合 PSR-4 标准的文件发出警告。
通过修复这些文件名及其将在 PSR-4 标准警告中显示的 Controller 名称,应该可以解决您的问题。
关于Laravel 组件构造函数方法仅在本地环境中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66613999/