Smarty是一個(gè)使用PHP寫出來的模板引擎,是業(yè)界最著名的PHP模板引擎之一。它分離了邏輯代碼和外在的內(nèi)容,提供了一種易于管理和使用的方法,用來將原本與HTML代碼混雜在一起PHP代碼邏輯分離。
如何將smarty安裝到MVC架構(gòu)中?
首先是composer.json
{ "require": { "smarty/smarty": "^3.1" }, // 自動(dòng)加載 // 可以在composer.json的autoload字段找那個(gè)添加自己的autoloader "autoload": { "psr-4": { "App\Controllers\": "Controllers/", "App\Models\": "Models/", "Tools\": "Tools/" } } }
Models/Users.php
<?php // model層數(shù)據(jù)庫操作演示 namespace AppModels; class Users { // 數(shù)據(jù)存入數(shù)據(jù)庫演示 public function store() { echo 'store into database'; } // 查詢數(shù)據(jù)庫演示 public function getUsername() { // 查詢數(shù)據(jù)庫 return 'test-data'; } }
Controllers/UserController.php
<?php namespace AppControllers; use AppModelsUsers; use Smarty; class UserController extends Smarty { public function create() { echo 'User create'; } public function getUser() { // 通過Model查詢數(shù)據(jù) $userModel = new Users; $username = $userModel->getUsername(); echo 'username:'.$username;exit; $this->setTemplateDir(dirname(__DIR__) . '/Views/'); $this->setCompileDir(dirname(__DIR__) . '/runtime/Compile/'); // 將$username顯示在對(duì)應(yīng)的一個(gè)HTML文件當(dāng)中,并且顯示出來 // 表現(xiàn)層 user/user.html // 將變量發(fā)送給模板(html文件) $this->assign('username', $username); $this->assign('age', 20); // 顯示模板 $this->display('user/user.html'); } }
Views/user/user.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2> {$username} </h2> <h3> {$age} </h3> </body> </html>
在本機(jī)瀏覽器中訪問