.php

.php

Beberapa waktu lalu, sempat terpikir oleh gw, untuk sistem (web) yang sederhana (dari segi fitur) __ yang mungkin __ terlalu boros jika dibikin pakai framework ataupun berorientasi objek sehingga dibuat alurnya prosedural saja, tapi strukturnya masih rapi, minimal ada pemisahan kode php dengan template. Tidak perlu memakai template engine yang sudah komplek seperti Smarty atau yang lainnya, karena ya itu terlalu boros (dilihat ukuran size aplikasinya).

So iseng-iseng gw coba bikin.

Jadi strukturnya kira-kira seperti ini :

Struktur sederhana
Struktur sederhana

Strukturnya mungkin seperti CodeIgniter (karena inspirasinya di sana), simple.templating.php adalah librari-nya, welcome_view.php adalah contoh file templatenya (HTML/web page) , dan file welcome.php yang terletak di luar folder lib dan views adalah contoh “controller”nya.

simple.templating.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
 
define('EXT'        , '.php') ;
define('VIEWPATH'   , 'views/') ;
 
/**
 * Load View
 *
 * @access	public
 * @param	string $file file location (no extension (.php))
 * @param	string $data array nor not
 * @param	mixed  $string print results (FALSE) or save results to string (TRUE)
 * @return	string
 */
 
function load_view($file,$data = NULL,$string = FALSE) {
    if (is_array($data)) {
        // this is like "value to variable", see my artcle on http://kohaci.com/2010/03/24/value-to-variable.html
        // check more on http://php.net/manual/en/function.extract.php
        extract($data) ;
    }
 
    ob_start();
    include ( VIEWPATH . $file . EXT );
    $content = ob_get_clean();
 
    if ($string)    return $content ;
    else            echo $content ;
}
 
/* End of file simple.templating.php */
/* Location: ./lib/simple.templating.php */

Jika di CodeIgniter, untuk me-load view dijalankan seperti ini :

$this->load->view($WEB_PAGE,$data) ;

Maka di simple template engine kali ini jalannya :

load_view($WEB_PAGE,$data) ;

Ataupun hasil templating disimpan dulu ke variable, di CodeIgniter :

$string = $this->load->view($WEB_PAGE,$data,FALSE) ;

Di simple template engine :

$string = load_view($WEB_PAGE,$data,FALSE) ;

Contoh view di welcome_view.php

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <?php echo $welcome ;?>
    </body>
</html>

Contoh “controller”nya di welcome.php

1
2
3
4
5
6
7
8
9
<?php
include 'lib/simple.templating.php';
 
$data['welcome'] = "halo ..." ;
 
load_view('welcome_view',$data) ;
 
/* End of file welcome.php */
/* Location: ./welcome.php */

Download kode di atas di sini.

Semoga bermanfaat.