因為升級成 Codeignitor4(以下全稱為ci4) 加上習慣使用 smarty4,因此在 view表上決定使用 smarty4(以下皆稱smarty)。
程式碼來源於[1],有小部分修改。
異動的檔案有三個,在app/目錄下
├── Config
│ ├── Services.php <== 註記服務
├── Libraries
│ └── CI4Smarty.php <== 叫用smarty物件
├── ThirdParty
└── smarty <== smarty4裝在這裡
...
└── libs
├── Autoloader.php <== 讀取此檔即可
在writable/目錄下建立兩個可寫入的目錄
├── cache
├── templates_c
Config/Services.php
<?php namespace Config; use CodeIgniter\Config\Services as CoreServices; use CodeIgniter\Config\BaseConfig; use Config\App; use App\Libraries\CI4Smarty; require_once SYSTEMPATH . 'Config/Services.php'; class Services extends CoreServices { public static function SmartyEngine($getShared = true){ return ($getShared === true ? static::getSharedInstance('SmartyEngine') : new CI4Smarty()); } };
Libraries/CI4Smarty.php
<?php namespace App\Libraries; require_once APPPATH.'ThirdParty/smarty/libs/Autoloader.php'; use \Smarty_Autoloader; Smarty_Autoloader::register(); use \Smarty; class CI4Smarty extends Smarty { public function __construct() { parent::__construct(); parent::setTemplateDir(APPPATH . 'Views/'); parent::setCompileDir(WRITEPATH . 'templates_c/')->setCacheDir(WRITEPATH . 'cache/'); parent::setLeftDelimiter('{{'); parent::setRightDelimiter('}}'); } public function view($tpl_name) { parent::display($tpl_name); } }
設定寫入暫存檔目錄及cache,同時設定smart標記左右符號。
Controller 中叫用
service('SmartyEngine')->assign('ip',$ip)->assign('isipv6', $isipv6); service('SmartyEngine')->view('smarty_template.tpl');
SmartyEngine 預設採用靜態方式載入,如果想要創建新的 SmartyEngine,可寫成:
service('SmartyEngine',false);
結論是透過網友的幫忙,smarty+ci4 整合的不錯,也不難,祝大家使用愉快。