MVC開發模式以及Smarty模板引擎的使用

Linux 全局安裝 composerphp

將目錄切換到/usr/local/bin/目錄
    cd /usr/local/bin/
在 bin 目錄中下載 composer
    curl -sS https://getcomposer.org/installer | php
經過 composer.phar -v 查看 composer
修改成中國鏡像
    composer.phar config -g repo.packagist composer https://packagist.phpcomposer.com
最後我把composer.phar複製了一份,重命名爲composer
之後能夠直接用composer

MVC架構模式
控制器(Controller)- 負責轉發請求,對請求進行處理
視圖(View) - 界面設計人員進行圖形界面設計
模型(Model) - 程序員編寫程序應有的功能(實現算法等等)、數據庫專家進行數據管理和數據庫設計(能夠實現具體的功能)html

實現簡易模板引擎:前端

composer.jsonios

    {
      // 自動加載
      // 能夠在composer.json的autoload字段找那個添加本身的autoloader
      "autoload": {
        "psr-4": {
          "App\\Controllers\\": "Controllers/",
          "App\\Models\\": "Models/",
          "Tools\\": "Tools/"
        }
      }
    }

Models/Users.php程序員

    <?php
    // model層數據庫操做演示
    namespace App\Models;

    class Users
    {
        // 數據存入數據庫演示
        public function store()
        {
            echo 'store into database';
        }

        // 查詢數據庫演示
        public function getUsername()
        {
            // 查詢數據庫
            return 'test-data';
        }
    }

Controllers/UserController.php算法

    <?php
    namespace App\Controllers;

    use Tools\Tpl;
    use App\Models\Users;

    class UserController extends Tpl
    {
        public function create()
        {
            echo 'User create';
        }

        public function getUser()
        {
            // 經過Model查詢數據
            $userModel = new Users;
            $username = $userModel->getUsername();

            // 將$username顯示在對應的一個HTML文件當中,而且顯示出來
            // 表現層 user/user.html
            // 將變量發送給模板(html文件)
            $this->assign('username', $username);
            $this->assign('age', 20);
            // 顯示模板
            $this->display('user/user.html');
        }
    }

Views/user/user.html數據庫

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h2>
            {$username}
        </h2>
        <h3>
            {$age}
        </h3>
    </body>
    </html>

Tools/Tpl.phpjson

    <?php
    // 分配變量
    // 將變量發送給模板
    namespace Tools;

    class Tpl
    {
        protected $assign_vars = [];

        public function assign($tpl_var_name, $val)
        {
            $this->assign_vars[$tpl_var_name] = $val;
        }

        public function display($tpl_name)
        {
            // Views/user/$tpl_name
            $className = get_called_class(); // App\Controllers\UserController
            $dirName = strtolower(substr(substr($className, 16), 0, -10)); // user
            $dir = dirname(__DIR__) . '/Views/' . $dirName . '/' . $tpl_name;
            // file_get_contents
            $content = file_get_contents($dir);
            // preg_replace
            foreach ($this->assign_vars as $tpl_var_name => $val) {
                $content = preg_replace('/\{\$' . $tpl_var_name . '\}/', '<?php echo $this->assign_vars["' . $tpl_var_name . '"]; ?>', $content);
            }
            // compile
            $compile = dirname(__DIR__) . '/runtime/Compile/' . md5($tpl_name) . '.php';
            file_put_contents($compile, $content);
            // include
            include $compile;
        }
    }

Smarty模板引擎的使用api

服務端開發部分演示
Smarty引擎的安裝
變量的分配和加載顯示模板
以插件形式擴展Smarty
緩存控制技術數組



smarty.php

    <?php
    /**
     * Created by PhpStorm.
     */
    session_start();
    require './libs/Smarty.class.php';

    $smarty = new Smarty();

    // 簡單配置 初始化設置
    $smarty->setTemplateDir('./Views');
    $smarty->setCompileDir('./runtime/Compile');
    $smarty->setConfigDir('./Config');
    $smarty->addPluginsDir('./Plugins');
    $smarty->setCacheDir('./runtime/Cache');

    $smarty->caching = 1;//開啓緩存
    $smarty->setCacheLifetime(60*60*24);
    $smarty->left_delimiter = '{';
    $smarty->right_delimiter = '}';

    // 緩存機制
    if (!$smarty->isCached('extends.html', $_SERVER['REQUEST_URI'])) {

        // 數據庫查詢
        $data = [[]];

        // 使用 
        $smarty->assign([
            'username' => 'test-data',
            'age' => 20
        ]);

        // 數組
        $smarty->assign('arr1', [1, 2, 3]);
        $smarty->assign('arr2', ['id' => 1, 'username' => 'zhangsan', 'age' => 30]);
        $smarty->assign('users', [
            ['id' => 1, 'username' => 'zhangsan', 'age' => 30],
            ['id' => 2, 'username' => 'lisi', 'age' => 40]
        ]);

        $smarty->assign('hobby_ids', [1, 2, 3]);
        $smarty->assign('hobby_output', ['看書', '敲代碼', '看視頻']);
        $smarty->assign('options', [
            1 => '看書',
            2 => '敲代碼',
            3 => '看視頻'
        ]);

        // 註冊function
        $smarty->registerPlugin('function', 'font', function ($attributes) {
           $text = $attributes['text'];
           $color = $attributes['color'] ?? 'black';
           return '<span style="color: ' . $color . '">' . $text . '</span>';
        });

        // 註冊變量修飾器
        $smarty->registerPlugin('modifier', 'link', function ($text, $href, $isCapitalize = false) {
           $return = '<a href="' . $href . '">' . $text . '</a>';
           if ($isCapitalize) {
               return ucwords($return);
           }
           return $return;
        });
        
        // 註冊塊狀函數
        $smarty->registerPlugin('block', 'link', function ($attributes, $text) {
           $href = $attributes['href'];
           if (!is_null($text)) {
               return '<a href="' . $href . '">' . $text . '</a>';
           }
        });

        // 對象
        $smarty->assign('obj', $smarty);

        $smarty->assign('text', 'This is a paragraph!');

        $smarty->display('smarty.html');
        $smarty->display('loop.html');
        $smarty->display('single_tag_func.html');
        $smarty->display('modifier.html');
        $smarty->display('block_func.html');
        $smarty->display('plugins.html');
        $smarty->assign('users', $data);
    }
    $smarty->clearCache('extends.html', $_SERVER['REQUEST_URI']);
    $smarty->clearAllCache();
    $smarty->display('extends.html', $_SERVER['REQUEST_URI']);

前端開發部分演示

註釋和變量的使用smarty.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>
        <!-- 模板註釋被*星號包圍,而兩邊的星號又被定界符包圍 -->
        {*$username*}
        {$username}
    </h2>
    <h3>
        <!-- 變量 -->
        {$age}
    </h3>
    <hr>
        <!-- 索引數組 -->
        arr1:
        {$arr1[1]}
    <hr>
        <!-- 關聯數組 -->
        arr2:
        {$arr2['username']}
        {$arr2.username}
    <hr>
        <!-- 對象 -->
        Object:
        {var_dump($obj->getTemplateDir())}
    <hr>
        <!-- 變量的運算 -->
        {$var = 100}
        {$var}
        {$foo = $var + 200}
        {$foo}
    <hr>
        {$foo}
    <hr>
        <!-- 保留變量的使用 -->
        $_GET:
        {var_dump($smarty.get)}
    <hr>
        $_POST:
        {var_dump($smarty.post)}
    <hr>
        $_REQUEST:
        {var_dump($smarty.request)}
    <hr>
        COOKIE:
        {var_dump($smarty.cookies)}
    <hr>
        SESSION:
        {var_dump($smarty.session)}
    <hr>
        SERVER:
        {var_dump($smarty.server)}
    <hr>
        ENV:
        {var_dump($smarty.env)}
    <hr>
        {time()}
        {$smarty.now}
    <hr>
        <!-- 加載配置文件後,配置文件中的變量須要用兩個井號「#」包圍或者是 smarty的保留變量$smarty.config.來調用 -->
        {config_load file='base.conf'}
        {#FONT_SIZE#}
        {$smarty.config.FONT_COLOR}
</body>
</html>

流程控制的使用loop.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>流程控制</title>
</head>
<body>
   <!--  使用{if}處理分支結構 -->
    {$number = 200}
    {if $number === 100}
        gt
    {else if $number == 200}
        This number is 200
    {else}
        This number is not 100
    {/if}

    {$bool = false}
    {if not $bool}
        not
    {/if}

    {if $number is not even}
        odd
    {/if}

    {if $number is not odd}
        even
    {/if}

    {if $number mod 2 == 0}
        even
    {/if}

    {if $number is not odd by 3}
        odd
    {/if}

    <!-- 使用{for}處理循環 -->
    {for $i = 5 to 4 step 2}
        {$i}
    {forelse}
        no loop
    {/for}

    <!-- 使用{while}處理循環 -->
    {while $number > 195}
        {$number--}
    {/while}

    <!-- 使用{foreach}遍歷數組 -->
    {foreach $arr2 as $key => $val}
        {if $val@first}
            {*break*}
            {continue}
        {/if}
        {$key}:{$val}
        {$val@key}
        {$val@index}
        {$val@iteration}
        {$val@first}
        {$val@last}
        {$val@show}
        {$val@total}
    {foreachelse}
        data does not exist
    {/foreach}

    <!-- 使用{section}遍歷數組 -->
    {section name=key loop=$arr1}
        {$arr1[key]}
    {/section}

    {section name=key loop=$users2 step=-1 max=2}
        id: {$users[key].id}
        username: {$users[key].username}
        age: {$users[key].age}
        {$smarty.section.key.index}
        {$smarty.section.key.iteration}
        {$smarty.section.key.rownum}
        {$smarty.section.key.index_prev}
        {$smarty.section.key.index_next}
    {sectionelse}
        no loop
    {/section}

</body>
</html>

經常使用標籤函數的使用single_tag_func.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>經常使用標籤函數的使用</title>
</head>
<body>
    {assign var="name" value="Jason"}
    {assign "name" "Jason Lee"}
    {$name}

    {append var="arr1" value=4 index="3"}
    {var_dump($arr1)}

    {ldelim}$name{rdelim}

    {html_checkboxes name="hobby" values=$hobby_ids output=$hobby_output selected=$hobby_ids}
    {html_checkboxes name="hobby" options=$options selected=$hobby_ids}
    {html_image width="50" height="50" alt="Google" href="http://www.google.com" file="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"}
    {html_options name="hobby" values=$hobby_ids output=$hobby_output selected=2}
    {html_options name="hobby" options=$options selected=2}
    {html_radios name="hobby" options=$options selected=2}
    {html_select_date}
    {html_select_time}
    {html_table loop=$arr1 cols=2 rows=3}
    {mailto address="86267659@qq.com" subject="test" text="給我發郵件" cc="123123@qq.com"}
    {math equation="x + y" x = 100 y = 200}
</body>
</html>

變量修飾器的使用modifier.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>變量修飾器的使用</title>
</head>
<body>
    {$str="123123\nthIs is string."}
    <hr>
    {$str|capitalize:true:true}
    <hr>
    {$str|capitalize:true:true|cat:'.'}
    <hr>
    {$str|count_characters}
    <hr>
    {$str|count_paragraphs}
    <hr>
    {$str|count_sentences}
    <hr>
    {$str|count_words}
    <hr>
    {$str2|default:'Not Data Yet'}
    <hr>
    {time()|date_format:'%Y-%m-%d %H:%M:%S'}
    <hr>
    {$chinese = '中文'}
    {$chinese|from_charset:'utf-8'|to_charset:'gb2312'}
    <hr>
    {$str|indent:10:'---'}
    <hr>
    {$str|lower|upper}
    <hr>
    {$str2="This is p1.\nThis is p2."}
    {$str2|nl2br}
    <hr>
    {$str|regex_replace:'/\d+/':' '}
    <hr>
    {$str|replace:'123123':'000'}
    <hr>
    {$str|spacify:'-'}
    <hr>
    {$float='10.0020398475'}
    {$float|string_format:'%.2f'}
    <hr>
    {$str3='a     b     c'}
    {$str3|strip:'-'}
    <hr>
    {$tag='<b>Font</b>'}
    {$tag|strip_tags}
    <hr>
    {$bigstr='123123123123123123ahjfdashfksdhfkjsdhjkfshfjkhsd'}
    {$bigstr|truncate:10:'---':true:true}
    <hr>
    {$tag|escape|unescape}
    <hr>
    {$bigstr|wordwrap:10:"\n":true}
</body>
</html>

塊函數的使用block_func.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>塊函數的使用</title>
</head>
<body>
    {textformat indent='4' indent_first='10' indent_char='-' wrap='10' wrap_char='<hr>' wrap_cut=true assign='var'}
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaa
    {/textformat}

    {*$var*}

    {nocache}
        {time()}
    {/nocache}
    <hr>
    {time()}
</body>
</html>

插件的開發plugins.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {font text=$text color='#123123'}
    {$text|link:'http://www.baidu.com'}
    {link href='http://www.baidu.com'}
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
        aaaaaaaaaaaaaaaaa
    {/link}
</body>
</html>

Smarty模板引擎插件的開發:
一、使用registerPlugin( )方法擴充插件格式


二、在smarty模板的libs/plugins/目錄下建立函數插件文件

block.link.php

function smarty_block_link($attributes, $text)
{
    $href = $attributes['href'];
    if (!is_null($text)) {
        return '<a href="' . $href . '">' . $text . '</a>';
    }
}

function.font.php

function smarty_function_font($attributes)
{
    $text = $attributes['text'];
    $color = $attributes['color'] ?? 'black';
    return '<span style="color: ' . $color . '">' . $text . '</span>';
}

modifier.link.php

function smarty_modifier_link($text, $href, $isCapitalize = false)
{
    $return = '<a href="' . $href . '">' . $text . '</a>';
    if ($isCapitalize) {
        return ucwords($return);
    }
    return $return;
}

模板繼承的使用
extends.html

!-- 使用{extends}函數實現模板繼承
合併子模板和父模板的{block}標籤內容 -->

{extends file="layout.html"}
{block name="title"}
    Article {$smarty.block.parent}
{/block}

{block name="content"}
    Article List
    {$smarty.get.page}
    {*nocache*}
        {time()}
    {*/nocache*}
    {time()|date_format:'%H:%M:%S' nocache}
{/block}

layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{block name="title"} - Imooc{/block}</title>
</head>
<body>
    <header>
        menu
    </header>
    {block name="content"}{/block}
    <footer>
        copyright
    </footer>
</body>
</html>

緩存機制
開啓緩存
  $smarty -> caching = 1|2|0;
  $smarty -> setCacheDir("./cache");
  $smarty->setCacheLifetime(300); // 5分鐘,以秒爲單位,-1永不過時
  $smarty -> display('index.tpl');
  $smarty -> display('index.tpl', $_SERVER['REQUEST_URI']);

相關函數   isCached()   clearCache()   clearAllCache()

相關文章
相關標籤/搜索