首先是composer.json
{ "require": { "smarty/smarty": "^3.1" }, // 自動加載 // 可以在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 App\Models\Users; use Smarty; class UserController extends Smarty { public function create() { echo 'User create'; } public function getUser() { // 通過Model查詢資料 $userModel = new Users; $username = $userModel->getUsername(); echo 'username:'.$username;exit; $this->setTemplateDir(dirname(__DIR__) . '/Views/'); $this->setCompileDir(dirname(__DIR__) . '/runtime/Compile/'); // 將$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>
在本機瀏覽器中訪問

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/84985.html
標籤:PHP
