- argparse.ArgumentParser args AttributeError: ‘Namespace‘ object has no attribute ‘xxx‘
城俊BLOG
Python报错#DL-基础标签
文章目录报错解决参数不需要写全更多要求已经添加了命令参数,但还是报这个错误。报错解决原因可能是参数添加顺序不对。正确的顺序:#先创建parserparser=argparse.ArgumentParser(description='xxx')#再添加参数parser.add_argument('--model',default=
- classfinal加密失败,踩坑了,不妨进来看看
行云的逆袭
classfinalspringbootjar包加密踩坑加密失败
最近在使用classfinal加密springboot,执行成功了,但是反编译后还是能看到源码,很郁闷!加密之后,反编译还是能看到源码,头疼我采用的加密方式是插件方式,放上配置net.roseboyclassfinal-maven-plugin${classfinal.version}#org.springxingyunapplication.yml,application-dev.yml,app
- zynq和petalinux环境下控制gpio的两种方法
qqssbb123
petalinuxgpio
1,用Sysfs这个对MIO可用。查看,如果没用/sys目录可#mkdir/sys#mount-tsysfssysfs/sys/sys/class/gpio/gpiochipN/得到N=512,实际LEDGPIO是38拉低这个GPIO点亮LEDN+38=512+38=550echo550>/sys/class/gpio/exportechoout>/sys/class/gpio/gpio550/d
- CSS3学习教程,从入门到精通, CSS3入门介绍的语法知识点及案例(1)
知识分享小能手
前端开发网页开发编程语言如门css3学习csshtml5前端javahtml
CSS3入门介绍一、CSS3选择器1.1基本选择器/*元素选择器*/p{color:red;}/*类选择器*/.myClass{font-size:20px;}/*ID选择器*/#myId{background-color:yellow;}/*通用选择器*/*{margin:0;padding:0;}这是一个段落这是一个带有类的段落这是一个带有ID的段落1.2属性选择器/*属性选择器*/[href
- FLASK核心操作之ORM
爬山的小明
FlaskFlaskORM
ORM一、概要1、说明ORM,即Object-RelationalMapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候,就不需要再去和复杂的SQL语句打交道,只需简单的操作对象的属性和方法,2、核心模块SQLAlchemyORM和SQLAlchemyCoreCore是一种构建在表达式语言之上的一种API,一种SQL抽象工具包,允
- Redis 源码分析-内部数据结构 robj
笨手笨脚の
#Redisredis数据结构数据库redisObject44字节embStrraw
Redis源码分析-内部数据结构robjRedis中,一个database内的这个映射关系是用一个dict来维护的(ht[0])。dict的key固定用一种数据结构来表达就够了,即动态字符串sds。而value则比较复杂,为了在同一个dict内能够存储不同类型的value,这就需要一个通用的数据结构,这个通用的数据结构就是robj(全名redisObject)。#defineLRU_BITS24/
- 【贪心算法5】
m0_46150269
贪心算法算法
力扣738.单调递增的数字链接:link思路遇到c[i]>c[i+1]则c[i]–,然后就是给c[i+1]赋值‘9’;需要注意的是star初值问题,可见注释部分。classSolution{publicintmonotoneIncreasingDigits(intn){Strings=String.valueOf(n);char[]c=s.toCharArray();intstar=c.lengt
- 用Python写一个天气预报小程序
穿梭的编织者
Python脚本python小程序
一、界面效果二、完整代码importtkinterastkfromtkinterimportttkimportrequestsimportjsonfromdatetimeimportdatetimefromPILimportImage,ImageTkimportiofromttkbootstrapimportStyleclassWeatherApp:def__init__(self,root):s
- 手写一些常见算法
林tong学
算法排序算法java数据结构
手写一些常见算法快速排序归并排序Dijkstra自定义排序交替打印0和1冒泡排序插入排序堆排序快速排序publicclassMain{publicstaticvoidmain(String[]args){intnums[]={1,3,2,5,4,6,8,7,9};quickSort(nums,0,nums.length-1);}privatestaticvoidquickSort(int[]num
- 深入理解 OTSU 算法(大津法——最大类间方差法)
ZHauLee
机器学习算法计算机视觉人工智能
一、算法概述OTSU算法是一种用于图像分割的自动阈值选择算法,广泛应用于图像处理领域,特别是在二值化过程中。它是由日本学者大津展之(NobuyukiOtsu)在1979年提出,因此得名“OTSU算法”。二、算法原理OTSU算法的核心思想是通过遍历所有可能的阈值,将图像分割为前景(目标)和背景两部分,使得这两部分之间的类内方差(intra-classvariance)最小,或者说使得这两部分之间的类
- Leetcode Hot100 第40题 297.二叉树的序列化和反序列化
onlyzzr
暑期实习刷题记录leetcode深度优先算法
/***Definitionforabinarytreenode.*structTreeNode{*intval;*TreeNode*left;*TreeNode*right;*TreeNode(intx):val(x),left(NULL),right(NULL){}*};*/classCodec{public:intindex;//Encodesatreetoasinglestring.str
- 合并二叉树 迭代(leetcode 617
JohnFF
leetcode算法职场和发展
leetcode系列文章目录一、核心操作二、外层配合操作三、核心模式代码总结一、核心操作1.将右树的值加到左树上2.对两棵树的子节点进行筛选,如果都有则都加进去,如果左树没有则将右数的节点指针赋给左树,如果左树有右树没有则不用管提示:小白个人理解,如有错误敬请谅解!二、外层配合操作1.确保root1和root2都有值,所以当一棵树为空则返回另外一棵树三、核心模式代码代码如下:classSoluti
- Spring Cache的基本使用
奇怪的大象
面试学习路线阿里巴巴springjava后端
文章目录一、概述二、SpringCache的使用2.1环境搭建2.2缓存的读模式@Cacheable2.3自定义缓存配置
[email protected]@CacheEvict删除缓存2.6@Caching多个操作三、SpringCache的不足一、概述常见的缓存的框架有Redis、Memcached、Guava、Caffeine等等,各有各的优势。如果我们的程序想要使用缓存,就要与这些框架耦合。聪明
- 【动态规划1】
m0_46150269
动态规划算法
力扣509.斐波那契数链接:link思路这是一道经典的动态规划DP题,做动态有5步:1.确定dp[i]含义,表示第i个数的斐波那契数值是dp[i]2.dp数组初始化3.确定递推公式4.确定遍历顺序,从递推公式可以知道dp[i]是依赖dp[i-1]和dp[i-2],那么遍历的顺序一定是从前到后遍历的5.举例推导,草稿完成classSolution{publicintfib(intn){if(n<=1
- 【算法学习day10】
m0_46150269
算法学习
力扣202.快乐数链接:link思路这道题可能会遇到无限循环的情况,如何跳出循环是关键,我们可以用哈希表快速查询是否重复出现之前遇到的结果来结束循环。另外对数字的拆解也是解这道题的关键,下面来看题解吧。解:classSolution{publicbooleanisHappy(intn){Setset1=newHashSet0){inttemp=n%10;sum+=temp*temp;n/=10;}
- Leetcode1005:k次取反后最大化的数组和(贪心算法)
immortalize
leetcode算法题解答java算法贪心算法leetcode
Leetcode1005:k次取反后最大化的数组和题目:给你一个整数数组nums和一个整数k,按以下方法修改该数组:选择某个下标i并将nums[i]替换为-nums[i]。重复这个过程恰好k次。可以多次选择同一个下标i。以这种方式修改数组后,返回数组可能的最大和。思路:贪心算法代码如下:classSolution{publicintlargestSumAfterKNegations(int[]nu
- BigDecimal只覆盖整数部分或小数部分
支持未来
java算法开发语言
有个特殊处理需要把BigDecimal的整数部分和小数部分分开计算publicclassBdTest{publicstaticvoidmain(String[]args){BdBeanbt=newBdBean();bt.setBdA(4);System.out.println(bt.getB());bt.setBdA(0);System.out.println(bt.getB());bt.setB
- JButton追加事件监听
支持未来
JAVAActionList
画面和按钮生成publicclassmainTestClass{publicstaticJFramemain=newJFrame("テスト画面");//publicstaticJTextAreaResult=newJTextArea("",4,40);//publicstaticJButtonSubmit=newJButton("開始");/***メイン関数**@paramargs*/public
- 简单的网页链接爬虫
笑颜218
爬虫python简单
fromurllib.requestimporturlopenfromurllib.parseimporturljoinfromhtml.parserimportHTMLParser#自定义HTML解析器classLinkParser(HTMLParser):def__init__(self,base_url):super().__init__()self.base_url=base_url#基础
- java24种设计模式目录,为大家整理最全的24种设计模式详解,必收藏
高补
java24种设计模式目录
设计模式六大原则单一职责原则一个方法尽可能做一件事情,一般来说不应该让一个方法承担多个职责。单一职责原则的英文名称是SingleResponsibilityPrinciple,简称是SRP。单一职责原则的定义是:应该有且仅有一个原因引起类的变更。SRP的原话解释是:Thereshouldneverbemorethanonereasonforaclasstochange.单一职责原则提出了一个编写程
- DAY31 回溯算法 排列问题
Useee
leetcode数据结构算法c++
491.非递减子序列-力扣(LeetCode)这道题限制了nums的取值范围,所以可以使用数组来去重,如果范围过大要使用哈希表。classSolution{private:vector>result;vectorpath;voidbackTracking(vector&nums,intstartIndex){if(path.size()>1){result.push_back(path);}int
- DAY30 回溯算法 子集问题 Ⅰ
Useee
算法leetcodec++数据结构
93.复原IP地址-力扣(LeetCode)classSolution{private:vectorresult;voidbackTracking(string&s,intstartIndex,intpiontNum){if(piontNum==3){if(isUseful(s,startIndex,s.size()-1)){result.push_back(s);}return;}for(int
- SpringBoot整合MinIO实现文件的上传下载以及获取预览URL
.晚安.
springboot后端javaweb
SpringBoot整合MinIO实现文件的上传下载以及获取预览URLJDK17SpringBoot3参考https://min.io/docs/minio/linux/developers/java/API.html?ref=docs-redirect#uploadObject源码https://gitee.com/Uncommen/easy-min-io引入依赖在pom.xml中添加主要的依赖
- Day29 贪心算法 part03
2401_83448199
贪心算法算法
134.加油站本题有点难度,不太好想,推荐大家熟悉一下方法二代码随想录classSolution{publicintcanCompleteCircuit(int[]gas,int[]cost){intsum=0;intindex=0;intstar=0;inttotalgas=0;inttotalcost=0;for(inti=0;iratings[i]){result[i+1]=result[i
- Go语言分布式ID生成策略优选:UUID、Snowflake、XID、ObjectID、Krand性能对比评测
zhuyasen
golang分布式
在高并发应用场景下,如订单系统、分布式数据库主键、消息队列等,分布式ID的生成至关重要。本文将基于Go语言,对多种分布式ID生成方案进行基准测试(Benchmark),并分析其性能及适用场景,帮助开发者选择最优方案。常见分布式ID生成方案在Go语言生态中,常见的分布式ID生成方案包括:XID(github.com/rs/xid):基于MongoDBObjectID改进的方案,时间排序、唯一性强、无
- 怎么使用jwt,token以及redis进行续期?
曦月不可及?
java
怎么使用jwt,token以及redis进行续期?什么是jwt?什么是token?结合JWT、Token和Redis进行续期的一般步骤:生成JWT:用户登录成功后,服务器生成一个JWT,并返回给客户端。importio.jsonwebtoken.Jwts;importio.jsonwebtoken.SignatureAlgorithm;publicclassJwtUtil{privatestati
- QT系列教程(19) Qt MVC结构之QItemDelegate介绍
恋恋风辰
C++QTqtmvc开发语言
QItemDelegate当我们想重新实现一个代理时,可以子类化QItemDelegate。实现item编辑时特定的效果,比如在item编辑时我们设置一个QSpinBox返回。创建一个QApplication项目,然后我们新增一个类,类名叫做spinboxdelegate。classSpinBoxDelegate:publicQItemDelegate{Q_OBJECTpublic:explici
- 【架构思维基础:如何科学定义问题】
调皮的芋头
架构阿里云云计算大数据
架构思维基础:如何科学定义问题一、问题本质认知1.1问题=矛盾根据毛泽东《矛盾论》,问题本质是系统内部要素间既对立又统一的关系。例如:电商系统矛盾演变:90年代:商品供给不足vs消费需求增长00年代:商品丰富但信息匹配低效10年代:商品数量充足但质量需求升级1.2问题三维度publicclassProblem{//核心矛盾主体(如用户需求)privateCoreConflictmainConfli
- 每天一道算法题【蓝桥杯】【下降路径最小和】
桦0
题解算法蓝桥杯c++leetcode
思路使用dp表来解决问题为了方便填写dp表,多初始化一圈格子状态转移方程dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i-1][j+1]))+matrix[i-1][j-1];每个元素等于上一行元素最小的那个加上本格元素最后遍历最后一行dp表找最小值for(intj=1;jusingnamespacestd;classSolution{public:int
- xml
ColorPaper
各项IT技术杂项xmlcharacterattributesprocessingschemaencoding
TheExtensibleMarkupLanguage(XML)isageneral-purposespecificationforcreatingcustommarkuplanguages.[1]Itisclassifiedasanextensiblelanguagebecauseitallowsitsuserstodefinetheirownelements.Itsprimarypurpose
- HQL之投影查询
归来朝歌
HQLHibernate查询语句投影查询
在HQL查询中,常常面临这样一个场景,对于多表查询,是要将一个表的对象查出来还是要只需要每个表中的几个字段,最后放在一起显示?
针对上面的场景,如果需要将一个对象查出来:
HQL语句写“from 对象”即可
Session session = HibernateUtil.openSession();
- Spring整合redis
bylijinnan
redis
pom.xml
<dependencies>
<!-- Spring Data - Redis Library -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redi
- org.hibernate.NonUniqueResultException: query did not return a unique result: 2
0624chenhong
Hibernate
参考:http://blog.csdn.net/qingfeilee/article/details/7052736
org.hibernate.NonUniqueResultException: query did not return a unique result: 2
在项目中出现了org.hiber
- android动画效果
不懂事的小屁孩
android动画
前几天弄alertdialog和popupwindow的时候,用到了android的动画效果,今天专门研究了一下关于android的动画效果,列出来,方便以后使用。
Android 平台提供了两类动画。 一类是Tween动画,就是对场景里的对象不断的进行图像变化来产生动画效果(旋转、平移、放缩和渐变)。
第二类就是 Frame动画,即顺序的播放事先做好的图像,与gif图片原理类似。
- js delete 删除机理以及它的内存泄露问题的解决方案
换个号韩国红果果
JavaScript
delete删除属性时只是解除了属性与对象的绑定,故当属性值为一个对象时,删除时会造成内存泄露 (其实还未删除)
举例:
var person={name:{firstname:'bob'}}
var p=person.name
delete person.name
p.firstname -->'bob'
// 依然可以访问p.firstname,存在内存泄露
- Oracle将零干预分析加入网络即服务计划
蓝儿唯美
oracle
由Oracle通信技术部门主导的演示项目并没有在本月较早前法国南斯举行的行业集团TM论坛大会中获得嘉奖。但是,Oracle通信官员解雇致力于打造一个支持零干预分配和编制功能的网络即服务(NaaS)平台,帮助企业以更灵活和更适合云的方式实现通信服务提供商(CSP)的连接产品。这个Oracle主导的项目属于TM Forum Live!活动上展示的Catalyst计划的19个项目之一。Catalyst计
- spring学习——springmvc(二)
a-john
springMVC
Spring MVC提供了非常方便的文件上传功能。
1,配置Spring支持文件上传:
DispatcherServlet本身并不知道如何处理multipart的表单数据,需要一个multipart解析器把POST请求的multipart数据中抽取出来,这样DispatcherServlet就能将其传递给我们的控制器了。为了在Spring中注册multipart解析器,需要声明一个实现了Mul
- POJ-2828-Buy Tickets
aijuans
ACM_POJ
POJ-2828-Buy Tickets
http://poj.org/problem?id=2828
线段树,逆序插入
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;#define N 200010struct
- Java Ant build.xml详解
asia007
build.xml
1,什么是antant是构建工具2,什么是构建概念到处可查到,形象来说,你要把代码从某个地方拿来,编译,再拷贝到某个地方去等等操作,当然不仅与此,但是主要用来干这个3,ant的好处跨平台 --因为ant是使用java实现的,所以它跨平台使用简单--与ant的兄弟make比起来语法清晰--同样是和make相比功能强大--ant能做的事情很多,可能你用了很久,你仍然不知道它能有
- android按钮监听器的四种技术
百合不是茶
androidxml配置监听器实现接口
android开发中经常会用到各种各样的监听器,android监听器的写法与java又有不同的地方;
1,activity中使用内部类实现接口 ,创建内部类实例 使用add方法 与java类似
创建监听器的实例
myLis lis = new myLis();
使用add方法给按钮添加监听器
- 软件架构师不等同于资深程序员
bijian1013
程序员架构师架构设计
本文的作者Armel Nene是ETAPIX Global公司的首席架构师,他居住在伦敦,他参与过的开源项目包括 Apache Lucene,,Apache Nutch, Liferay 和 Pentaho等。
如今很多的公司
- TeamForge Wiki Syntax & CollabNet User Information Center
sunjing
TeamForgeHow doAttachementAnchorWiki Syntax
the CollabNet user information center http://help.collab.net/
How do I create a new Wiki page?
A CollabNet TeamForge project can have any number of Wiki pages. All Wiki pages are linked, and
- 【Redis四】Redis数据类型
bit1129
redis
概述
Redis是一个高性能的数据结构服务器,称之为数据结构服务器的原因是,它提供了丰富的数据类型以满足不同的应用场景,本文对Redis的数据类型以及对这些类型可能的操作进行总结。
Redis常用的数据类型包括string、set、list、hash以及sorted set.Redis本身是K/V系统,这里的数据类型指的是value的类型,而不是key的类型,key的类型只有一种即string
- SSH2整合-附源码
白糖_
eclipsespringtomcatHibernateGoogle
今天用eclipse终于整合出了struts2+hibernate+spring框架。
我创建的是tomcat项目,需要有tomcat插件。导入项目以后,鼠标右键选择属性,然后再找到“tomcat”项,勾选一下“Is a tomcat project”即可。具体方法见源码里的jsp图片,sql也在源码里。
补充1:项目中部分jar包不是最新版的,可能导
- [转]开源项目代码的学习方法
braveCS
学习方法
转自:
http://blog.sina.com.cn/s/blog_693458530100lk5m.html
http://www.cnblogs.com/west-link/archive/2011/06/07/2074466.html
1)阅读features。以此来搞清楚该项目有哪些特性2)思考。想想如果自己来做有这些features的项目该如何构架3)下载并安装d
- 编程之美-子数组的最大和(二维)
bylijinnan
编程之美
package beautyOfCoding;
import java.util.Arrays;
import java.util.Random;
public class MaxSubArraySum2 {
/**
* 编程之美 子数组之和的最大值(二维)
*/
private static final int ROW = 5;
private stat
- 读书笔记-3
chengxuyuancsdn
jquery笔记resultMap配置ibatis一对多配置
1、resultMap配置
2、ibatis一对多配置
3、jquery笔记
1、resultMap配置
当<select resultMap="topic_data">
<resultMap id="topic_data">必须一一对应。
(1)<resultMap class="tblTopic&q
- [物理与天文]物理学新进展
comsci
如果我们必须获得某种地球上没有的矿石,才能够进行某些能量输出装置的设计和建造,而要获得这种矿石,又必须首先进行深空探测,而要进行深空探测,又必须获得这种能量输出装置,这个矛盾的循环,会导致地球联盟在与宇宙文明建立关系的时候,陷入困境
怎么办呢?
 
- Oracle 11g新特性:Automatic Diagnostic Repository
daizj
oracleADR
Oracle Database 11g的FDI(Fault Diagnosability Infrastructure)是自动化诊断方面的又一增强。
FDI的一个关键组件是自动诊断库(Automatic Diagnostic Repository-ADR)。
在oracle 11g中,alert文件的信息是以xml的文件格式存在的,另外提供了普通文本格式的alert文件。
这两份log文
- 简单排序:选择排序
dieslrae
选择排序
public void selectSort(int[] array){
int select;
for(int i=0;i<array.length;i++){
select = i;
for(int k=i+1;k<array.leng
- C语言学习六指针的经典程序,互换两个数字
dcj3sjt126com
c
示例程序,swap_1和swap_2都是错误的,推理从1开始推到2,2没完成,推到3就完成了
# include <stdio.h>
void swap_1(int, int);
void swap_2(int *, int *);
void swap_3(int *, int *);
int main(void)
{
int a = 3;
int b =
- php 5.4中php-fpm 的重启、终止操作命令
dcj3sjt126com
PHP
php 5.4中php-fpm 的重启、终止操作命令:
查看php运行目录命令:which php/usr/bin/php
查看php-fpm进程数:ps aux | grep -c php-fpm
查看运行内存/usr/bin/php -i|grep mem
重启php-fpm/etc/init.d/php-fpm restart
在phpinfo()输出内容可以看到php
- 线程同步工具类
shuizhaosi888
同步工具类
同步工具类包括信号量(Semaphore)、栅栏(barrier)、闭锁(CountDownLatch)
闭锁(CountDownLatch)
public class RunMain {
public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
fin
- bleeding edge是什么意思
haojinghua
DI
不止一次,看到很多讲技术的文章里面出现过这个词语。今天终于弄懂了——通过朋友给的浏览软件,上了wiki。
我再一次感到,没有辞典能像WiKi一样,给出这样体贴人心、一清二楚的解释了。为了表达我对WiKi的喜爱,只好在此一一中英对照,给大家上次课。
In computer science, bleeding edge is a term that
- c中实现utf8和gbk的互转
jimmee
ciconvutf8&gbk编码
#include <iconv.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
int code_c
- 大型分布式网站架构设计与实践
lilin530
应用服务器搜索引擎
1.大型网站软件系统的特点?
a.高并发,大流量。
b.高可用。
c.海量数据。
d.用户分布广泛,网络情况复杂。
e.安全环境恶劣。
f.需求快速变更,发布频繁。
g.渐进式发展。
2.大型网站架构演化发展历程?
a.初始阶段的网站架构。
应用程序,数据库,文件等所有的资源都在一台服务器上。
b.应用服务器和数据服务器分离。
c.使用缓存改善网站性能。
d.使用应用
- 在代码中获取Android theme中的attr属性值
OliveExcel
androidtheme
Android的Theme是由各种attr组合而成, 每个attr对应了这个属性的一个引用, 这个引用又可以是各种东西.
在某些情况下, 我们需要获取非自定义的主题下某个属性的内容 (比如拿到系统默认的配色colorAccent), 操作方式举例一则:
int defaultColor = 0xFF000000;
int[] attrsArray = { andorid.r.
- 基于Zookeeper的分布式共享锁
roadrunners
zookeeper分布式共享锁
首先,说说我们的场景,订单服务是做成集群的,当两个以上结点同时收到一个相同订单的创建指令,这时并发就产生了,系统就会重复创建订单。等等......场景。这时,分布式共享锁就闪亮登场了。
共享锁在同一个进程中是很容易实现的,但在跨进程或者在不同Server之间就不好实现了。Zookeeper就很容易实现。具体的实现原理官网和其它网站也有翻译,这里就不在赘述了。
官
- 两个容易被忽略的MySQL知识
tomcat_oracle
mysql
1、varchar(5)可以存储多少个汉字,多少个字母数字? 相信有好多人应该跟我一样,对这个已经很熟悉了,根据经验我们能很快的做出决定,比如说用varchar(200)去存储url等等,但是,即使你用了很多次也很熟悉了,也有可能对上面的问题做出错误的回答。 这个问题我查了好多资料,有的人说是可以存储5个字符,2.5个汉字(每个汉字占用两个字节的话),有的人说这个要区分版本,5.0
- zoj 3827 Information Entropy(水题)
阿尔萨斯
format
题目链接:zoj 3827 Information Entropy
题目大意:三种底,计算和。
解题思路:调用库函数就可以直接算了,不过要注意Pi = 0的时候,不过它题目里居然也讲了。。。limp→0+plogb(p)=0,因为p是logp的高阶。
#include <cstdio>
#include <cstring>
#include <cmath&
Inspired by this article I started to play around a bit to integrate the Smarty template engine into the Zend Framework. My ambition was to minimize the required code in the controller actions but stay close to the given Zend_View API. I also wanted to integrate the Smarty caching feature. Here is the code I came up with.
Class location
The class file is named by my company (Travello) and is placed in the Travello directory beneath the Zend Framework library include path. Its advantage is that the class will be auto loaded in my setup.
Class definition and constructor
Let's start with the class definition and the constructor part. My class Travello_View_Smarty is extending the Zend_View_Abstract class. In the constructor the parent constructor from Zend_View_Abstract is called first. After that a Smarty object is instantiated, configured and stored in a private attribute.
Please note that I use a configuration object from the object store to get the configuration data for Smarty.
Implement _run() method
The method _run() is the only method that needs to be implemented in any subclass of Zend_View_Abstract. It is called automatically within the render() method. My implementation just uses the display() method from Smarty to generate and output the template.
Overwrite assign() method
The next part is an overwrite of the assign() method from Zend_View_Abstract, which works in a similar way. The big difference is that the values are assigned to the Smarty object and not to the $this->_vars variables array of Zend_View_Abstract.
Overwrite escape() method
The next part is an overwrite of the escape() method from Zend_View_Abstract. It works both for string and array values and also uses the escape() method from the Zend_View_Abstract. The advantage of this is that I don't have to care about each value of an array to get properly escaped.
Print the output
The next method output() is a wrapper on the render() method from Zend_View_Abstract. It just sets some headers before printing the output.
Use Smarty caching
The last two methods were created to simply integrate the Smarty caching mechanism in the View class. With the first one you can check for cached template and with the second one you can set the caching on or of.
That was the complete code of my Travello_View_Smarty class.
How to use the class
The usage of this class is quite simple. In your bootstrap file you can initialize it like this. The $viewConfig is used to setup the Zend_View paths. After creation the object is registered in the object store for later usage.
Within your controller an action method could look like this.
Conclusion
That was basically it. I have a couple of ideas how to extend this solution, but it already does the work for me. Any comments are welcome.
Updated on April 18, 2006
Please have also a look at the follow-up article on Integrating Sarty and ez Components with the Zend Framework.
Digg This!
Comments
PHPDeveloper.org just pointed out a related article on caching using Smarty. This will fit nicely with what Ralf has written here.
currently I am using the ezcConfiguration and ezcConfigurationIniReader from the ezComponents
http://ez.no/doc/components/view/latest/(file)/introduction_Configuration.html
To integrate the ezComponents within the Zend Framework I put the ezComponents directory in my include_path and use a slightly different __autoload() function:
To use the Configuration component I set it up and store the configuration object in the object store of the Zend Framework.
That is basically it.
HTH, Ralf
If you redefined the Smarty Tags to "<?" and "?>" and uses Templates it allows you to see a really clean design in your design editor (there are other ways to do that, but this is quick!!). Templates also make it easy to develop huge interface changes in all your application on the fly without touching your code (the customers like that!!!) and taking advantage of the smarty cache management.
Another thing that helped me was the idea of Tom Anderson of adding a "T" block for Internationalization support. With this you, can even make your design in English and tagged all translatable text with "T" blocks and after use a Smarty-T- block plugin to support your application in different languages. I used in Japanese and I developed my own t block plug in like this:
The i18ngettext is a function that search into the localization files and returns the content with the translated phrase if it exists. I rewrite the i18ngettext in order to cached the files.
In design time text will look like:
<?t?>Translate me<?/T?>
Bye,
Hermann
For example if you created a Zend_View_Helper_MakeUrl and want to invoke it through a template:
<a href="{makeUrl('index','login')}">Login</a>
I don't think it is possible by using your approach because the helper method are unknown to the smarty object.
In my code is assigned a Zend_View Object that includes all output variables to the smarty object by doing:
By doing this, smarty will automatically invoke the Zend_View::__call() method to unknown funktions, and that invokes the helper methods. the disadvantage is that you have to use:
<a href="{$view->makeUrl('index','login')}">Login</a>
which is a little more code, but it works for me.
One more Question: Did anyone manage to make TemplateLite (former SmartyLite) working with ZF?
regards, Marc
thanks for your comments on internationalization. Sounds very good to me. For myself, I haven't come to that part yet, but your approach sounds reasonable to me.
Until now what I did was to assign an array called "translate" to Smarty and to access the translation via {$template.to_be_translate}.
Best Regards,
Ralf
you could easily assign the View object to Smarty as well by doing something like this in the _run() method:
But I haven't tested this yet, so I might be wrong.
Best Regards,
Ralf
I just wanted to drop a comment to tell you how much I appreciate this tutorial. I was in the process of starting a new project, and wanted to use a more stuctured approach. I was all ready using smarty without the Zend framework.
I knew I wanted to use the framework in my new project, but also wanted to use smarty. Your tutorial was the deciding factor in my changing to the Zend Framework. After spending most of yesterday downloading, and installing Apache I was able to get it working. (After spending a few hours learning how th configure Apache. Oh well, the burden of running your own server.)
Anyway, thanks again.
Troy
However, I have made just 4 methods in my class:
three that you have mentioned (__construct, assign, _run) and also _script() - to avoid redundant Zend_Exception:
The main issue in your code (IMHO) is the following: you are extending the Zend_View_Abstract interface by adding several new methods that are not present in the abstract class. This cannot be considered a problem until one day you decide that Smarty is no good - and you should fall back to using Zend_View instead.
Then you can extend the Zend_View and make Torello_View_Zend class with stub methods, and that will be ok - but I think you should mention this in your article.
"Uncaught exception 'Zend_Exception' with message 'File "Zend/View/Helper/run.php" was not found"
Seems that the file run.php is not part of the Zend Framework.
Any Idea ?
Help please.
What can you say about design of my sites?
<a href="http://eumcci.com/htm/images/artical/data/index.php">sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=1">adult sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=2">sex toy party</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=3">sex toy for man</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=4">homemade sex toy</a>
What can you say about design of my sites?
<a href="http://eumcci.com/htm/images/artical/data/index.php">sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=1">adult sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=2">sex toy party</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=3">sex toy for man</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=4">homemade sex toy</a>
What can you say about design of my sites?
<a href="http://eumcci.com/htm/images/artical/data/index.php">sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=1">adult sex toy</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=2">sex toy party</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=3">sex toy for man</a>
<a href="http://eumcci.com/htm/images/artical/data/?page=4">homemade sex toy</a>
I am currently developing my own framework based on ZF and decided to use TemplateLite as template engine.
In response to octavian82 question, I give you Phlame_View_Tpl integrating TemplateLite with Zend View.
You can view the source here:
http://dev.inetive.pl/phlame/Phlame_View_Tpl.phps
And here is some example.
The template: http://dev.inetive.pl/phlame/test_template.tpl
The example code: http://dev.inetive.pl/phlame/tpl_test.phps
And the result: http://dev.inetive.pl/phlame/tpl_test.php
I would appreciate any comments and ideas.