使用具有依赖注入的 Plates PHP

我想使用依赖注入将Plates实例传递给带有 PHP-DI 的控制器,该控制器与我的路由系统Simple Router集成。我试图注入一个 Plates 实例,但出现此错误:


<?php


namespace Controllers;


use \League\Plates\Engine;

use \League\Plates\Template\Template;

use \League\Plates\Extension\Asset;


class Controller {


  public function __construct(\League\Plates\Engine $templates)

  {

    $this->templates = $templates;

  }


?>

未捕获的 LogicException:模板名称“home”无效。尚未定义默认目录


我该如何解决这个问题?我还需要使用 asset() 方法传递资产路径。任何帮助将不胜感激。


更新


感谢 jcHache 的帮助,我用这个 DI 代码在我的基本控制器中管理了一个 Plates 实例的注入:


<?php 


// config.php

return [

  League\Plates\Engine::class => DI\create()

    ->constructor(TEMPLATE_ROOT)

    ->method('loadExtension', DI\get('League\Plates\Extension\Asset')),

  League\Plates\Extension\Asset::class => DI\create()

    ->constructor(APP_ROOT),

];


index.php 文件


<?php 


use Pecee\SimpleRouter\SimpleRouter;

use DI\ContainerBuilder;


$container = (new \DI\ContainerBuilder())

  ->useAutowiring(true)

  ->addDefinitions('config.php')

  ->build();


SimpleRouter::enableDependencyInjection($container);


这很好,但我面临一个问题,我找不到解决办法。我得到这个与板块资产加载器相关的错误,它似乎被实例化了不止一次。我已经用我的基本控制器扩展了我的控制器,在其中实例化了资产加载器,但我认为这不是问题吗?有解决办法吗?


未捕获的 Pecee\SimpleRouter\Exceptions\NotFoundHttpException:模板函数名称“资产”已注册


慕的地10843
浏览 89回答 1
1回答

万千封印

Plates引擎工厂需要一个视图文件夹参数(参见Plates doc):所以你必须在你的PHP-DI配置文件中添加这个创建:对于板 V4:// config.phpreturn [&nbsp; &nbsp; // ...&nbsp; &nbsp; \League\Plates\Engine::class => function(){&nbsp; &nbsp; &nbsp; &nbsp; return League\Plates\Engine::create('/path/to/templates', 'phtml');&nbsp; &nbsp; },];对于 Plates V3,我会尝试:// config.phpreturn [&nbsp; &nbsp; // ...&nbsp; &nbsp; \League\Plates\Engine::class => function(){&nbsp; &nbsp; &nbsp; &nbsp; return new League\Plates\Engine('/path/to/templates');&nbsp; &nbsp; },];或者// config.phpreturn [&nbsp; &nbsp; // ...&nbsp; &nbsp; \League\Plates\Engine::class =>&nbsp; DI\create()&nbsp; &nbsp; &nbsp; &nbsp;->constructor('/path/to/templates')&nbsp; &nbsp; ,];设计说明:就我个人而言,我不会对模板引擎使用依赖注入,我认为在基本控制器类中实例化 Plates 引擎会更好。namespace controllers;use League\Plates\Engine;abstract class BaseController&nbsp;{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* @var \League\Plates\Engine&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $templates;&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->templates=new Engine(\TEMPLATE_ROOT);&nbsp; &nbsp; &nbsp; &nbsp; $this->templates->loadExtension(new \League\Plates\Extension\Asset(\APP_ROOT));&nbsp; &nbsp; }&nbsp; &nbsp; protected function renderView(string $viewname, array $variables=[])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->templates->render($viewname,$variables);&nbsp; &nbsp; }}对于使用Plates以下内容的子控制器:namespace controllers;class MyController extends BaseController{&nbsp; &nbsp; public function index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->renderView('home');&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP