溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么將smarty安裝到MVC架構(gòu)中

發(fā)布時間:2021-03-05 10:39:45 來源:億速云 閱讀:127 作者:小新 欄目:編程語言

小編給大家分享一下怎么將smarty安裝到MVC架構(gòu)中,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

Smarty是一個使用PHP寫出來的模板引擎,是業(yè)界最著名的PHP模板引擎之一。它分離了邏輯代碼和外在的內(nèi)容,提供了一種易于管理和使用的方法,用來將原本與HTML代碼混雜在一起PHP代碼邏輯分離。

如何將smarty安裝到MVC架構(gòu)中?

首先是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層數(shù)據(jù)庫操作演示
namespace App\Models;
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 App\Controllers;
use App\Models\Users;
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顯示在對應的一個HTML文件當中,并且顯示出來
        // 表現(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>
    <h3>
        {$username}
    </h3>
    <h4>
        {$age}
    </h4>
</body>
</html>

以上是“怎么將smarty安裝到MVC架構(gòu)中”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI