如何将smarty安装到MVC架构中(代码示例)
导读:收集整理的这篇文章主要介绍了如何将smarty安装到MVC架构中(代码示例),觉得挺不错的,现在分享给大家,也给大家做个参考。Smarty是一个使用PHP写出来的模板引擎,是业界最著名的php模板引擎之一。它分离了逻辑代码和外在的内容,提供...
收集整理的这篇文章主要介绍了如何将smarty安装到MVC架构中(代码示例),觉得挺不错的,现在分享给大家,也给大家做个参考。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 'store into database';
}
// 查询数据库演示 public function getUsername() {
// 查询数据库 return 'test-data';
}
}
Controllers/UserController.php
?phpnamespace 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>
head>
meta charset="UTF-8">
title>
Title/title>
/head>
body>
h2>
{
$username}
/h2>
h3>
{
$age}
/h3>
/body>
/html>
在本机浏览器中访问
更多相关php知识,请访问php教程!
以上就是如何将smarty安装到MVC架构中(代码示例)的详细内容,更多请关注其它相关文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何将smarty安装到MVC架构中(代码示例)
本文地址: https://pptw.com/jishu/596182.html
