Smarty integration into the codeigniter
เนื่องจากที่ทำงานใช้ Smarty เป็น template engine แต่โค้ดส่วนใหญ่โครงเริ่มเสียเพราะ เปลี่ยนคนทำมาหลายมือ เมื่อมาถึงผมก็เลยคิดว่าจะป้องกันปัญหาเดิมๆที่มีอยู่โดยใช้ framework ที่เป็น MVC มาช่วย ตัวที่เลือกใช้ก็ codeigniterเพราะชอบมานานล่ะ ง่ายดีไม่เครงครัดจนเกินไป ที่นี้ลองมาดูกัน วิธีใช้ Smarty มาแทนที่ view เดิมของ codeigniter
ขั้นแรก ไปดาวน์โหลด codeigniter ที่นี่ครับ http://codeigniter.com/downloads/ ผมใช้ 1.7.2 นะครับ
ขั้นที่สอง ไปโหลด smarty ที่นี่ครับ http://www.smarty.net/download.php ผมใช้ Smarty-2.6.26 นะครับ ลอง 3 แล้วมีปัญหาครับ
ก็แตกซิบทั้ง 2 ตัว แล้วเอา libs ของ smarty ไปใส่ไว้ใน libraries ของ codeigniter
ขั้นที่สาม rename เป็น libs -> Smarty ทีนี้ path ที่ได้ ก็จะเป็นประมาณนี้ [CI]/application/libraries/Smarty
ขั้นที่สี่ สร้าง File: Cismarty.php ขึ้นมาใน path [CI]/application/libraries/Cismarty.php แล้วใส่โค้ดนี้ครับ
< ?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
require_once(APPPATH . 'libraries/Smarty/Smarty.class.php');
class Cismarty extends Smarty
{
function __construct()
{
$this - >
template_dir = APPPATH . 'views/';
$this - >
compile_dir = APPPATH . 'templates_c/';
$this - >
// should be false for production $this->force_compile = true; // should be false for production $this->ALLOW_CONSTANTS = true ; $this->assign( 'APPPATH', APPPATH ); $this->assign( 'BASEPATH', BASEPATH ); } }
compile_check = true;
?>
ขั้นที่ห้า ต่อมาเป็นการทดสอบโค้ดนะครับ
สร้างไฟล์ home.php โดยใส่โค้ดนี้
load->library('cismarty');
$this->cismarty->assign('some_var', 'ta-aum.com');
$this->cismarty->display('some.tpl');
สร้างไฟล์ some.tpl ที่โฟลเดอร์ view นะครับ ใส่โค้ดนี้ครับ
Yeah! It’s work!
Powered by {$some_var}
แล้วลองรันดูนะครับ
อ้างอิงจาก http://www.jquerytips.com/2008/12/17/codigniter-with-smarty/

