[精讚] [會員登入]
218

[PHP] codeignitor4+ smarty4

這篇整合 php 的framework codeignitor4 + smarty4。

分享此文連結 //n.sfs.tw/16028

分享連結 [PHP] codeignitor4+ smarty4@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2022-12-27 21:23:52 最後編修
2022-12-27 15:23:18 By 張○○
 

 

因為升級成 Codeignitor4(以下全稱為ci4) 加上習慣使用 smarty4,因此在 view表上決定使用 smarty4(以下皆稱smarty)。

程式碼來源於[1],有小部分修改。

異動的檔案有三個,在app/目錄下

├── Config
│   ├── Services.php  <== 註記服務
├── Libraries
│   └── CI4Smarty.php  <== 叫用smarty物件
├── ThirdParty
    └── smarty <== smarty4裝在這裡
        ...
        └── libs
            ├── Autoloader.php  <== 讀取此檔即可

在writable/目錄下建立兩個可寫入的目錄

└── 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 整合的不錯,也不難,祝大家使用愉快。

 

參考資料

[1] https://forum.codeigniter.com/thread-76323.html

END

你可能感興趣的文章

[PHP] UTF8中取出字串中特定的字數 要將字串,例如資料庫取出的TEXT,取出特定的字數

利用 php 木馬作為駭客攻擊的手法 利用 php 木馬作為駭客攻擊的手法

[PHP] 陣列排序 sort, ksort, asort, usort... 簡單的記錄PHP的陣列排序,因為常常會用到。

[PHP] 使用FTP PHP 上使用 FTP 的寫法

[PHP] 處理mail 函式的標題中文字亂碼 PHP的mail函式若標題有中文字得先處理過,否則收信者會看到亂碼

[PHP] 將字串的部分加上遮罩的函式 有些資料會想要隱藏部分的字元,例如身分證號或信用卡號、電話等。我寫了一個函式來完成這個功能。

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

使用Google尋找你的手機 這近發現google竟然可以用來找android的手機,而且不需要經過什麼設定或安裝軟體。

安裝SPHINX支援中文 新版本的 sphinx 和舊版不同,網路上很多範例和教學是不能用的。此文是安裝和設定方法分享

[Wildfly10] 發佈war檔 deploy war file onto wildfly10

「許功蓋」的字以及源由 有玩過電腦一段時間的人,都聽過這個人(有一天我才發現7年級的竟然都不認識這個

只會買到爛貨的政府採購法 政府採購的公開招標,常常就只能比價格不能比品牌,只能比價格不能比品質,只能比價格不能比口碑,只能比價格不能比信用...