简体   繁体   English

如何在PHP中更好地使用Smarty?

[英]how to use Smarty better with PHP?

I found that using Smarty with PHP, sometimes extra time will need to be used for 我发现将Smarty与PHP结合使用时,有时需要花费更多时间

1) using quite different syntax than PHP itself 1)使用与PHP本身完全不同的语法
2) need to check small cases, because documentation doesn't give finer details, such as for "escape" 2)需要检查小的情况,因为文档没有提供更详细的信息,例如“转义”

http://www.smarty.net/manual/en/language.modifier.escape.php http://www.smarty.net/manual/zh/language.modifier.escape.php

it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. 它并没有说转义:“ quotes”仅适用于双引号或单引号,因此您需要编写代码对其进行测试。 Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped. 同样对于转义的情况:“ javascript”-无法确切说明其转义内容和方式。

3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again. 3)对于复杂的事情,需要编写辅助函数或修饰符,因此需要创建新文件并最终在PHP中重新进行。

by the way, does using Smarty provide a good speed up over use PHP alone? 顺便说一句,与单独使用PHP相比,使用Smarty是否可以提供良好的速度? thanks. 谢谢。

First, PHP is a templating language. 首先,PHP是一种模板语言。 Keep that in mind when you talk about using a template system for your PHP-based web applications. 在谈论为基于PHP的Web应用程序使用模板系统时,请记住这一点。

The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously. 我听说过使用ANY模板引擎的唯一“真实”论据是,它们为模板操作提供了一种更简单的语言,如果您有不了解PHP并且您不信任它们的模板设计人员,这将非常方便学会明智地使用PHP。

Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. 关于这些论点,我认为如果您的模板设计者没有能力学习足够的PHP用于模板设计,则您可能应该考虑寻找新的模板设计者。 Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. 此外,PHP本身为控制语句提供了不同的语法,您可以在模板中或在代码中使用控制语句。 For example: 例如:

<? foreach($array as $key => $val): ?>
    <?= $val ?>
<? endforeach; ?>

VS: VS:

<?php
    foreach($array as $key => $val) {
        echo $val;
    }

?>

Personally, I believe that templating engines arose in PHP because: 我个人认为,PHP中出现了模板引擎,因为:

  1. That's way that other languages do it 其他语言就是这样
  2. Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this. 更好的PHP程序员意识到,他们需要一种在表示和应用程序逻辑之间进行分隔的方法,而模板是实现此目的的简便方法。

The first reason is just kinda silly. 第一个原因是有点傻。 The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. 第二个原因可以通过少量的自我控制甚至对应用程序中分离层的必要性的基本理解而克服。 The MVC design pattern is one way of approaching this problem. MVC设计模式是解决此问题的一种方法。 As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen. 至于自我控制,我的规则是只有必要的循环和if语句会被使用,以及过滤,转义,格式化屏幕输出的函数。

Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. 广泛使用Smarty之后,老实说,与解决方案相比,它总是给我带来更多障碍。 If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code. 如果有的话,切换到基于PHP的模板实际上减少了模板和代码的开发时间。

I don't like templating engines. 我不喜欢模板引擎。 I find them very lossy and resource-intensive for PHP. 我发现它们对PHP来说非常有损和资源密集型。

With MediaWiki, around version 1.6.x we backed off using Smarty by default and just use PHP's built-in templating, with a great improvement in performance. 对于MediaWiki,在版本1.6.x左右,我们默认情况下不再使用Smarty,而仅使用PHP的内置模板,从而极大地提高了性能。

I've found that most of what people want to do with a templating system (add links, change colors, remove text or sections of the page) are better done with a simple system of event hooks. 我发现大多数人想要使用模板系统(添加链接,更改颜色,删除文本或页面的某些部分)都可以通过简单的事件挂钩系统来完成。

Laconica, the open microblogging platform, doesn't do any templating by default. Laconica,开放的微博平台,默认情况下不做任何模板。 We have a plugin for people who are crazy for templating. 我们为那些为模板疯狂的人们提供了一个插件。

Smarty is certainly one of the best template engines out there. Smarty当然是最好的模板引擎之一。 In my experience though people would be well advised to think their use cases through more thoroughly before they use any templating engine on top of PHP at all. 以我的经验,尽管如此,我们还是建议人们在使用PHP之上的任何模板引擎之前,应更彻底地考虑其用例。

First, PHP itself is perfect for templates. 首先,PHP本身非常适合模板。 Pretty much the only justification for using another templating engine is if you're allowing untrusted users to create or edit templates, since they could execute all kinds of badness. 使用另一个模板引擎的唯一理由几乎是,如果您允许不信任的用户创建或编辑模板,因为它们可能会执行各种错误。 So, if your project has user-editable templates, use Smarty. 因此,如果您的项目具有用户可编辑的模板,请使用Smarty。 If not, stick with PHP. 如果没有,请坚持使用PHP。

If your problem is separation of code and layout, I suggest you look into implementing a lightweight MVC-style execution model. 如果您的问题是代码和布局的分离,建议您考虑实施轻量级的MVC风格的执行模型。 Or, to put it more condescendingly, if you have deeper logic code in your template, it's probably time to do some refactoring. 或者,更贴切地说,如果您的模板中包含更深的逻辑代码,那么可能是时候进行一些重构了。

Performance is another consideration. 性能是另一个考虑因素。 Yes, rendering a Smarty template comes with a cost. 是的,渲染Smarty模板需要付费。 But after it's done, the output should be cached, leading you to improved execution times. 但是,完成后,应将输出缓存,从而缩短执行时间。 Same goes for PHP templates. PHP模板也是如此。 PHP allows you to implement all kinds of granular caching models through the use of its output buffers. PHP使您可以通过使用其输出缓冲区来实现各种粒度缓存模型。 But beware of premature optimization: do that only after you're code complete and have identified what the actual bottlenecks are! 但是要提防过早的优化:只有在代码完成并确定了实际瓶颈之后,才可以这样做!

The biggest cost when using Smarty or any other engine comes in the form of developer time. 使用Smarty或任何其他引擎时,最大的花费来自开发人员的时间。 It's another layer of complexity and inevitably you will find yourself in situations where you have to trick the engine into doing what you could have accomplished within pure PHP all along. 这是另一层复杂性,在不可避免的情况下,您将不得不欺骗引擎以完成在纯PHP中可以完成的工作。

I like template engines and think they should be used, but in the particular case of Smarty, I think it's waste of time, because it's not a significant improvement over PHP as templating language: 我喜欢模板引擎,并认为应该使用它们,但是在Smarty的特殊情况下,我认为这是浪费时间,因为与模板语言相比,它不是对PHP的重大改进:

  • The new syntax is still based around old concept of special tags inserted in random places in the document. 新语法仍然基于插入到文档中随机位置的特殊标签的旧概念。
  • Because Smarty does not understand HTML's syntax/structure, it cannot not help you to create valid/well-formed HTML. 因为Smarty无法理解HTML的语法/结构,所以它无法帮助您创建有效/格式正确的HTML。 Smarty's tags violate HTML's syntax, so once you add them, other standard tools can't help you either. Smarty的标签违反了HTML的语法,因此一旦添加它们,其他标准工具也将无法为您提供帮助。
  • Smarty's output, just like in PHP, is insecure (unescaped) by default and you have to remember to add |escape everywhere where you output data in HTML. 就像在PHP中一样,Smarty的输出默认情况下是不安全的(未转义),并且您必须记住在以HTML输出数据的任何地方添加|escape

There's one particular PHP template engine that I've fallen in love with, which fixes all those problems: PHPTAL . 我爱上了一个特定的PHP模板引擎,它解决了所有这些问题: PHPTAL

It's still something new you have to learn, and it's a depenency for your application, but I think having XSS and ill-formedness problems solved makes it worth the trouble. 它仍然是您必须学习的新知识,并且对您的应用程序来说是一种依赖,但是我认为解决XSS和格式错误会使其值得一试。

PHPTAL just like Smarty is compiled once to PHP and cached, so performance is comparable to raw PHP. 就像Smarty一样,PHPTAL可以一次编译成PHP并进行缓存,因此性能与原始PHP相当。

Pros 优点

  • No PHP in your HTML files (Allows both PHP and HTML identing) HTML文件中没有PHP(允许同时识别PHP和HTML)
  • Pipes {$var|default:"None selected"} {$var|urlencode} 管道{$ var |默认:“未选择”} {$ var | urlencode}
  • Foreachelse: {foreach item=row from=$results}{$row.name}<br>{foreachelse}No results{/foreach} Foreachelse:{foreach item = row from = $ results} {$ row.name} <br> {foreachelse}没有结果{/ foreach}
  • Themable websites/pages (Using only CSS has it limits) 可用的网站/页面(仅使用CSS有限制)

Cons 缺点

  • Other language syntax 其他语言语法
  • Not always obvious code {"Ymd"|strftime:$timestamp} {$array|@var_dump} 并非总是显而易见的代码{“ Ymd” | strftime:$ timestamp} {$ array | @var_dump}
  • Slight overhead 轻微的开销

I can highly recommend the "template" approach(mVc), but both Smarty and plain PHP are up for the task. 我强烈建议您使用“模板”方法(mVc),但是Smarty和纯PHP都可以完成此任务。

Using Smarty as a templating engine will probably not be as performant as not using it, as it is an extra layer of software, ie, a templating language on top of a, erm, another templating language. 将Smarty用作模板引擎可能不会像不使用它那样表现出色,因为它是软件的额外一层,即在另一种模板语言erm之上的模板语言。 On the other hand, if you use the caching feature properly you could realise overall performance gains. 另一方面,如果正确使用缓存功能,则可以实现整体性能提升。

Smarty templates are pre-compiled before being output to the browser, which involves writing temporary files to disk. Smarty模板在输出到浏览器之前会进行预编译,这涉及将临时文件写入磁盘。 This step surely penalises performance, at least a little. 此步骤肯定会降低性能,至少会降低一点。

If you are confident in your ability to keep implementation and presentation separate, and have no real interest in server-side caching, you should probably just use pure php templating. 如果您对保持实现和表示形式分离的能力充满信心,并且对服务器端缓存没有真正的兴趣,则应该只使用纯PHP模板。 Some MVC frameworks such as Zend Framework have their own PHP-like templating systems. 某些MVC框架(例如Zend Framework)具有自己的类似于PHP的模板系统。

On the other hand, smarty is a decent way to enforce a neat separation of presentation from implementation, particularly where it's unclear as to what belongs where. 另一方面,聪明是一种不错的方法,可以将表示与实现完全分开,特别是在不清楚所属位置的情况下。 It might help discipline you to enforce this necessary separation. 这可能有助于您纪律以强制执行此必要的分离。

That said, I use Smarty in most of my PHP projects, as it reminds me of Java-Server Tag Libraries (JSTL), which I'm very, very used to, and fond of. 就是说,我在大多数PHP项目中都使用Smarty,因为它使我想起了Java-Server Tag Libraries(JSTL),我非常,非常喜欢它。

As far as I know Smarty is one of the best template engines speed wise. 据我所知,Smarty是速度明智的最佳模板引擎之一。 Maybe it takes a while to get used to it. 也许需要一段时间才能习惯它。 But if you are not working on the system alone and the amount of html and style files is huge it speeds up the development significantly. 但是,如果您不是一个人在系统上工作,并且html和样式文件的数量巨大,那么它将大大加快开发速度。

While working on my last project the design was changes a couple of times but logics was the same. 在进行上一个项目时,设计进行了几次更改,但逻辑是相同的。 I guess that's the best example when Smarty or any other template engine helps a lot. 我想这是Smarty或任何其他模板引擎有很大帮助的最佳示例。

Personally I use Blitz for templating. 我个人使用Blitz进行模板制作。 On the site the author claims it is the fastest templating engine and provides a (biased?) chart over performance between different templating systems for PHP. 在该网站上,作者声称它是最快的模板引擎,并提供了一个(不同的?)针对PHP的不同模板系统之间的性能图表。 I haven't used smarty myself, but this may give you some hints on its performance. 我自己没有使用过聪明的人,但这可能会给您一些有关其性能的提示。

http://alexeyrybak.com/blitz/blitz_en.html http://alexeyrybak.com/blitz/blitz_en.html

尝试将Smarty与MVC模式(例如Codeigniter)一起使用,它比核心PHP更好

Using a Smarty or not is more or less a philosophical position. 是否使用一个聪明人或多或少是一个哲学立场。

I use it, although I don't use much functionality. 我使用它,尽管我不使用太多功能。 Using it this way, templates tend to be be very simple. 用这种方式,模板往往非常简单。 Pass an associative array with parameters, iterate through its components and insert required elements in the result page. 传递带参数的关联数组,遍历其组件,然后在结果页面中插入所需的元素。 This keeps templates clean and (hopefully) free of business logic. 这样可以使模板保持干净,并且(希望)没有业务逻辑。

Additionally, extending Smarty is quite simple. 此外,扩展Smarty非常简单。

As an example, I added a styles parameter to the fetch() to have a fetchUsingStyle(). 作为示例,我在fetch()中添加了一个styles参数以具有fetchUsingStyle()。 This allows me to switch between different layouts of a site quite easily. 这使我可以轻松地在网站的不同布局之间切换。

Furthermore, my fetchUsingStyle() searches various locations for a template: First tries to find the current style. 此外,我的fetchUsingStyle()在各个位置搜索模板:首先尝试查找当前样式。 If not found, it tries to load the template using a default style. 如果找不到,它将尝试使用默认样式加载模板。 Last, it tries to locate a pure static dummy file, a placeholder for something to be implemented later. 最后,它尝试找到一个纯静态的虚拟文件,这是以后要实现的东西的占位符。

Why use a template engine when you can just use your html files and inject php code where you need it? 当您只可以使用html文件并在需要的地方注入php代码时,为什么还要使用模板引擎? you can do this with Psttt! 您可以使用Psttt做到这一点! templating engine for php php的模板引擎

full source code here http://github.com/givanz/psttt 完整的源代码在这里http://github.com/givanz/psttt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM