如何实例化Illuminate\Contracts\View\Factory?

How to instantiate Illuminate\Contracts\View\Factory?

当我想实例化 Factory 时出现此错误。我需要实例化,因为有一个方法,make() 来渲染 blade 个文件。

[Symfony\Component\Debug\Exception\FatalThrowableError] Cannot instantiate interface Illuminate\Contracts\View\Factory

源代码

<?php

namespace App\Core;

use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;
use Illuminate\Contracts\View\Factory as ViewFactory;

class PDFGenerator
{

    private $view;

    public function __construct()
    {
        $this->view = new ViewFactory();
        $this->generatePDF();
    }

    public function generatePDF()
    {

        $html = $this->loadView('template');

    public function loadView($view, $data = array(), $mergeData = array(), $encoding = null){
        return $this->view->make($view, $data, $mergeData)->render();
    }
}

您似乎对 factory/interface 的工作方式有误解。 接口的要点是你不要实例化它,你只有带有参数的方法名称,所以每个实现它的classes都有统一的接口.

在这种情况下,如果您查看 Illuminate\Contracts\View\Factory,您会发现这里没有真正的处理,只有 "Okay, this is what this method will do, what inputs it expected and what output will be given" 的代码。您会看到没有提到如何做,实现该接口的 class 是应该知道如何做的人,而不是接口。


为了解决你的问题

当你想要呈现视图时,你有 2 个选项

  1. 使用view()helper function。 (首选)
  2. 使用 View Facades
  3. 中的 View::make() 方法