为了账号安全,请及时绑定邮箱和手机立即绑定

使用具有依赖注入的 Plates PHP

使用具有依赖注入的 Plates PHP

PHP
慕的地10843 2021-10-22 12:50:31
我想使用依赖注入将Plates实例传递给带有 PHP-DI 的控制器,该控制器与我的路由系统Simple Router集成。我试图注入一个 Plates 实例,但出现此错误:<?phpnamespace 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.phpreturn [  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:模板函数名称“资产”已注册
查看完整描述

1 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

Plates引擎工厂需要一个视图文件夹参数(参见Plates doc):


所以你必须在你的PHP-DI配置文件中添加这个创建:


对于板 V4:


// config.php

return [

    // ...

    \League\Plates\Engine::class => function(){

        return League\Plates\Engine::create('/path/to/templates', 'phtml');

    },

];

对于 Plates V3,我会尝试:


// config.php

return [

    // ...

    \League\Plates\Engine::class => function(){

        return new League\Plates\Engine('/path/to/templates');

    },

];

或者


// config.php

return [

    // ...

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

       ->constructor('/path/to/templates')

    ,

];

设计说明:


就我个人而言,我不会对模板引擎使用依赖注入,我认为在基本控制器类中实例化 Plates 引擎会更好。


namespace controllers;


use League\Plates\Engine;


abstract class BaseController 

{

    /**

     * @var \League\Plates\Engine

     */

    protected $templates;


    public function __construct()

    {

        $this->templates=new Engine(\TEMPLATE_ROOT);

        $this->templates->loadExtension(new \League\Plates\Extension\Asset(\APP_ROOT));

    }


    protected function renderView(string $viewname, array $variables=[])

    {

        return $this->templates->render($viewname,$variables);

    }

}

对于使用Plates以下内容的子控制器:


namespace controllers;


class MyController extends BaseController

{

    public function index()

    {

        return $this->renderView('home');

    }

}


查看完整回答
反对 回复 2021-10-22
  • 1 回答
  • 0 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信