Linux 全局安装 composer
将目录切换到/usr/local/bin/目录 cd /usr/local/bin/ 在 bin 目录中下载 composer curl -sS https://getcomposer.org/installer | php 通过 composer.phar -v 查看 composer 修改为中国镜像 composer.phar config -g repo.packagist composer https:packagist.phpcomposer.com 最后我把composer.phar复制了一份,重命名为composer 以后可以直接用composer
MVC架构模式
控制器(Controller)- 负责转发请求,对请求进行处理
视图(View) - 界面设计人员进行图形界面设计
模型(Model) - 程序员编写程序应有的功能(实现算法等等)、数据库专家进行数据管理和数据库设计(可以实现具体的功能)
实现简易模板引擎:
composer.json
{ 自动加载 可以在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'; } 查询数据库演示 function getUsername() { 查询数据库 return test-data; } }
Controllers/UserController.php
<? App\Controllers; use Tools\Tpl; use App\Models\Users; UserController extends Tpl { function create() { echo User create function getUser() { 通过Model查询数据 $userModel = new Users; $username = $userModel->getUsername(); 将$username显示在对应的一个HTML文件当中,并且显示出来 表现层 user/user.html 将变量发送给模板(html文件) $this->assign(usernameage',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>
Tools/Tpl.php
<? 分配变量 将变量发送给模板 Tools; Tpl { protected $assign_vars = []; function assign($tpl_var_name,$val) { $this->assign_vars[$tpl_var_name] = $val; } function display($tpl_name) { Views/user/$tpl_name $className = get_called_class(); App\Controllers\UserController $dirName = strtolower(substr(substr($className,1)">16),1)">0,-10)); user $dir = dirname(__DIR__) . /Views/' . $dirName . / . $tpl_name; file_get_contents $content = file_get_contents($dir); preg_replace foreach ($this->assign_vars as $tpl_var_name => $val) { $content = preg_replace(/\{\$' . $tpl_var_name . \}/<?php echo $this->assign_vars[""]; ?> compile $compile = dirname(__DIR__) . /runtime/Compile/' . md5($tpl_name) . .php; file_put_contents($compile,$content); include include $compile; } }
Smarty模板引擎的使用
服务端开发部分演示
Smarty引擎的安装
变量的分配和加载显示模板
以插件形式扩展Smarty
缓存控制技术
smarty.php
<?/** * Created by PhpStorm. */ session_start(); require './libs/Smarty.class.php'; $smarty = Smarty(); 简单配置 初始化设置 $smarty->setTemplateDir('./Views'); $smarty->setCompileDir('./runtime/Compile'$smarty->setConfigDir('./Config'$smarty->addPluginsDir('./Plugins'$smarty->setCacheDir('./runtime/Cache'); $smarty->caching = 1;开启缓存 $smarty->setCacheLifetime(60*60*24$smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; 缓存机制 if (!$smarty->isCached('extends.html',1)">$_SERVER['REQUEST_URI'])) { 数据库查询 $data = [[]]; 使用 $smarty->assign([ 'username' => 'test-data','age' => 20 ]); 数组 $smarty->assign('arr1',[1,2,3]); $smarty->assign('arr2',['id' => 1,'username' => 'zhangsan','age' => 30$smarty->assign('users', [ ['id' => 1,'age' => 30],1)"> ['id' => 2,'username' => 'lisi','age' => 40] ]); $smarty->assign('hobby_ids',1)">$smarty->assign('hobby_output',['看书','敲代码','看视频'$smarty->assign('options',1)"> [ 1 => '看书',2 => '敲代码',3 => '看视频' 注册function $smarty->registerPlugin('function','font',1)">function ($attributes) { $text = $attributes['text']; $color = $attributes['color'] ?? 'black'; return '<span style="color: ' . $color . '">' . $text . '</span>'; }); 注册变量修饰器 $smarty->registerPlugin('modifier','link',1)">$text,1)">$href,1)">$isCapitalize = false$return = '<a href="' . $href . '">' . $text . '</a>'if ($isCapitalize) { return ucwords($return); } ; }); 注册块状函数 $smarty->registerPlugin('block',1)">$attributes,1)">$text$href = $attributes['href']; if (!is_null()) { return '<a href="' . ; } }); 对象 $smarty->assign('obj',1)">$smarty); $smarty->assign('text','This is a paragraph!'$smarty->display('smarty.html'); $smarty->display('loop.html'$smarty->display('single_tag_func.html'$smarty->display('modifier.html'$smarty->display('block_func.html'$smarty->display('plugins.html'$data); } $smarty->clearCache('extends.html',1)">]); clearAllCache(); $smarty->display('extends.html',1)">$_SERVER['REQUEST_URI']);
前端开发部分演示
注释和变量的使用smarty.html
<!DOCTYPE html> <html lang="en"head> meta charset="UTF-8"title>Title</bodyh2> <!-- 模板注释被*星号包围,而两边的星号又被定界符包围 --> {*$username*} {$username} h3 变量 {$age} hr 索引数组 arr1: {$arr1[1]} 关联数组 arr2: {$arr2['username']} {$arr2.username} 对象 Object: {var_dump($obj->getTemplateDir())} 变量的运算 {$var = 100} {$var} {$foo = $var + 200} {$foo} > {$foo} 保留变量的使用 $_GET: {var_dump($smarty.get)} $_POST: {var_dump($smarty.post)} $_REQUEST: {var_dump($smarty.request)} COOKIE: {var_dump($smarty.cookies)} SESSION: {var_dump($smarty.session)} SERVER: {var_dump($smarty.server)} ENV: {var_dump($smarty.env)} {time()} {$smarty.now} 加载配置文件后,配置文件中的变量需要用两个井号“#”包围或者是 smarty的保留变量$smarty.config.来调用 {config_load file='base.conf'} {#FONT_SIZE#} {$smarty.config.FONT_COLOR} html>
流程控制的使用loop.html
>流程控制> 使用{if}处理分支结构 {$number = 200} {if $number === 100} gt {else if $number == 200} This number is 200 {else} This number is not 100 {/if} {$bool = false} {if not $bool} not {/if} {if $number is not even} odd {/if} {if $number is not odd} even {/if} {if $number mod 2 == 0} even {/if} {if $number is not odd by 3} odd {/if} 使用{for}处理循环 {for $i = 5 to 4 step 2} {$i} {forelse} no loop {/for} 使用{while}处理循环 {while $number > 195} {$number--} {/while} 使用{foreach}遍历数组 {foreach $arr2 as $key => $val} {if $val@first} {*break*} {continue} {/if} {$key}:{$val} {$val@key} {$val@index} {$val@iteration} {$val@first} {$val@last} {$val@show} {$val@total} {foreachelse} data does not exist {/foreach} 使用{section}遍历数组 {section name=key loop=$arr1} {$arr1[key]} {/section} {section name=key loop=$users2 step=-1 max=2} id: {$users[key].id} username: {$users[key].username} age: {$users[key].age} {$smarty.section.key.index} {$smarty.section.key.iteration} {$smarty.section.key.rownum} {$smarty.section.key.index_prev} {$smarty.section.key.index_next} {sectionelse} no loop {/section} >
常用标签函数的使用single_tag_func.html
>常用标签函数的使用 {assign var="name" value="Jason"} {assign "name" "Jason Lee"} {$name} {append var="arr1" value=4 index="3"} {var_dump($arr1)} {ldelim}$name{rdelim} {html_checkboxes name="hobby" values=$hobby_ids output=$hobby_output selected=$hobby_ids} {html_checkboxes name="hobby" options=$options selected=$hobby_ids} {html_image width="50" height="50" alt="Google" href="http://www.google.com" file="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"} {html_options name="hobby" values=$hobby_ids output=$hobby_output selected=2} {html_options name="hobby" options=$options selected=2} {html_radios name="hobby" options=$options selected=2} {html_select_date} {html_select_time} {html_table loop=$arr1 cols=2 rows=3} {mailto address="86267659@qq.com" subject="test" text="给我发邮件" cc="123123@qq.com"} {math equation="x + y" x = 100 y = 200} >
变量修饰器的使用modifier.html
>变量修饰器的使用 {$str="123123\nthIs is string."} {$str|capitalize:true:true} {$str|capitalize:true:true|cat:'.'} {$str|count_characters} {$str|count_paragraphs} {$str|count_sentences} {$str|count_words} {$str2|default:'Not Data Yet'} {time()|date_format:'%Y-%m-%d %H:%M:%S'} {$chinese = '中文'} {$chinese|from_charset:'utf-8'|to_charset:'gb2312'} {$str|indent:10:'---'} {$str|lower|upper} {$str2="This is p1.\nThis is p2."} {$str2|nl2br} {$str|regex_replace:'/\d+/':' '} {$str|replace:'123123':'000'} {$str|spacify:'-'} {$float='10.0020398475'} {$float|string_format:'%.2f'} {$str3='a b c'} {$str3|strip:'-'} {$tag='b>Font'} {$tag|strip_tags} {$bigstr='123123123123123123ahjfdashfksdhfkjsdhjkfshfjkhsd'} {$bigstr|truncate:10:'---':true:true} {$tag|escape|unescape} {$bigstr|wordwrap:10:"\n":true} >
块函数的使用block_func.html
>块函数的使用 {textformat indent='4' indent_first='10' indent_char='-' wrap='10' wrap_char='' wrap_cut=true assign='var'} aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa {/textformat} {*$var*} {nocache} {time()} {/nocache} {time()} >
插件的开发plugins.html
{font text=$text color='#123123'} {$text|link:'http://www.baidu.com'} {link href='http://www.baidu.com'} aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa {/link} >
Smarty模板引擎插件的开发:
1、使用registerPlugin( )方法扩充插件格式
2、在smarty模板的libs/plugins/目录下创建函数插件文件
block.link.php
function smarty_block_link() { ]; )) { ; } }
function.font.php
function smarty_function_font(]; ; ; }
modifier.link.php
function smarty_modifier_link() { ); } ; }
模板继承的使用
extends.html
!-- 使用{extends}函数实现模板继承
合并子模板和父模板的{block}标签内容 -->
{extends file="layout.html"}
{block name="title"}
Article {$smarty.block.parent}
{/block}
{block name="content"}
Article List
{$smarty.get.page}
{*nocache*}
{time()}
{*/nocache*}
{time()|date_format:'%H:%M:%S' nocache}
{/block}
layout.html
>{block name="title"} - Imooc{/block}header menu {block name="content"}{/block} footer copyright >
缓存机制
开启缓存
$smarty -> caching = 1|2|0;
$smarty -> setCacheDir("./cache");
$smarty->setCacheLifetime(300); // 5分钟,以秒为单位,-1永不过期
$smarty -> display('index.tpl');
$smarty -> display('index.tpl',$_SERVER['REQUEST_URI']);
相关函数
isCached()
clearCache()
clearAllCache()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。