Home > Backend Development > PHP Tutorial > How to install smarty into MVC architecture (code example)

How to install smarty into MVC architecture (code example)

藏色散人
Release: 2023-04-08 10:38:01
forward
2656 people have browsed it

Smarty是一个使用PHP写出来的模板引擎,是业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。

如何将smarty安装到MVC架构中?

首先是composer.json

{
  "require": {
    "smarty/smarty": "^3.1"
  },
  // 自动加载
  // 可以在composer.json的autoload字段找那个添加自己的autoloader
  "autoload": {
    "psr-4": {
      "App\\Controllers\\": "Controllers/",
      "App\\Models\\": "Models/",
      "Tools\\": "Tools/"
    }
  }
}
Copy after login

Models/Users.php

<?php
// model层数据库操作演示
namespace App\Models;
class Users
{
    // 数据存入数据库演示
    public function store()
    {
        echo &#39;store into database&#39;;
    }
    // 查询数据库演示
    public function getUsername()
    {
        // 查询数据库
        return &#39;test-data&#39;;
    }
}
Copy after login

Controllers/UserController.php

<?php
namespace App\Controllers;
use App\Models\Users;
use Smarty;
class UserController extends Smarty
{
    public function create()
    {
        echo &#39;User create&#39;;
    }
    public function getUser()
    {
        // 通过Model查询数据
        $userModel = new Users;
        $username = $userModel->getUsername();
        echo &#39;username:&#39;.$username;exit;
        $this->setTemplateDir(dirname(__DIR__) . &#39;/Views/&#39;);
        $this->setCompileDir(dirname(__DIR__) . &#39;/runtime/Compile/&#39;);
        // 将$username显示在对应的一个HTML文件当中,并且显示出来
        // 表现层 user/user.html
        // 将变量发送给模板(html文件)
        $this->assign(&#39;username&#39;, $username);
        $this->assign(&#39;age&#39;, 20);
        // 显示模板
        $this->display(&#39;user/user.html&#39;);
    }
}
Copy after login

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>
Copy after login

在本机浏览器中访问

How to install smarty into MVC architecture (code example)

更多相关php知识,请访问php教程

The above is the detailed content of How to install smarty into MVC architecture (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template