Maison  >  Article  >  développement back-end  >  Comment installer smarty dans l'architecture MVC (exemple de code)

Comment installer smarty dans l'architecture MVC (exemple de code)

藏色散人
藏色散人avant
2020-01-27 13:30:412538parcourir

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/"
    }
  }
}

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;;
    }
}

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;);
    }
}

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>

在本机浏览器中访问

Comment installer smarty dans larchitecture MVC (exemple de code)

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer