Program Club

PHP에서 템플릿 시스템을 사용해야하는 이유는 무엇입니까?

proclub 2020. 12. 12. 11:40
반응형

PHP에서 템플릿 시스템을 사용해야하는 이유는 무엇입니까?


PHP에서 템플릿 시스템을 사용해야하는 이유는 무엇입니까?

내 질문의 이유는 PHP 자체가 기능이 풍부한 템플릿 시스템입니다. 왜 다른 템플릿 엔진을 설치해야합니까?

지금까지 찾은 유일한 두 가지 장점은 다음과 같습니다.

  1. 좀 더 깔끔한 구문 (때때로)
  2. 템플릿 엔진은 일반적으로 비즈니스 로직을 구현할만큼 강력하지 않으므로 우려 사항을 분리해야합니다. PHP로 템플릿을 작성하면 템플릿 원칙을 살펴보고 코드 수프 작성을 다시 시작할 수 있습니다.

... 그리고 둘 다 단점과 비교할 때 매우 무시할 수 있습니다.

작은 예 :

PHP

<h1><?=$title?></h1>
<ul>
  <? foreach ($items as $item) {?>
  <li><?=$item?></li>
  <? } ?>
</ul>

똑똑한

<h1>{$title}</h1>
<ul>
  {foreach item=item from=$items}
  <li>{$item}</li>
  {/foreach}
</ul>

정말 차이가 전혀 보이지 않습니다.


네, 말했듯이 PHP (템플릿 엔진) 내부에서 템플릿 엔진을 사용하도록 강요하지 않으면 쉽게 문제를 분리하고 중단 할 수 있습니다.

그러나 문제를 분리하는 데 문제가있는 동일한 사람들은 결국 HTML을 생성하여 smarty에게 공급하거나 Smarty에서 PHP 코드를 실행하므로 Smarty는 우려 분리 문제를 거의 해결하지 못합니다.

또한보십시오:


사람들이 템플릿 시스템을 사용하는 주된 이유는 프레젠테이션과 논리를 분리하기 위해서입니다. 그로부터 오는 몇 가지 이점이 있습니다.

첫째, 코드 흐름을 유지하는 것에 대해 걱정할 필요없이 원하는대로 작업을 이동할 수있는 웹 디자이너에게 템플릿을 전달할 수 있습니다. 그들은 PHP를 이해할 필요가 없습니다. 단지 특수 태그 만 남겨 두는 것만 알면됩니다. 몇 가지 태그에 대해 몇 가지 간단한 의미를 배워야 할 수도 있지만 전체 언어를 배우는 것보다 훨씬 간단합니다.

또한 페이지를 별도의 파일로 분할함으로써 프로그래머와 디자이너는 동시에 동일한 '페이지'에서 작업 할 수 있으며 충돌없이 필요에 따라 소스 제어에 체크인 할 수 있습니다. 디자이너는 프로그래머가 자신의 복사본에 대해 다른 잠재적 인 변경 사항을 변경하는 동안 안정적인 버전의 코드에 대해 템플릿 시각적 개체를 테스트 할 수 있습니다. 그러나이 사람들이 모두 같은 파일을 편집하고 다른 변경 사항을 병합해야한다면 문제가 발생할 수 있습니다.

또한 비즈니스 논리를 프레젠테이션 논리에서 멀리 유지하는 데 좋은 프로그래밍 관행을 적용합니다. 비즈니스 논리를 프레젠테이션과 혼합하면 나중에 다르게 표시해야하는 경우 추출하는 데 더 많은 시간이 걸립니다. RSS / ATOM 피드, JSON 또는 AJAX 응답, 핸드 헬드 장치 용 WML 등 웹 앱의 다양한 프레젠테이션 모드가 요즘 점점 인기를 얻고 있습니다. 템플릿 시스템을 사용하면 종종 완전히 템플릿으로 수행 할 수 있으며 아무것도 변경하지 않거나 거의 변경하지 않을 수 있습니다. 그밖에.

그러나 모든 사람이 이러한 혜택을 필요로하거나 감사하는 것은 아닙니다. Java / Python / Ruby / etc에 비해 PHP의 장점은 웹 페이지에 로직이 포함 된 웹 페이지를 빠르게 해킹 할 수 있다는 것입니다.


논리를 분리하기 위해 PHP가 아닌 템플릿을 사용하는 것은 말도 안됩니다. 개발자가 비즈니스 뷰 로직 분리가 무엇인지, 어떻게해야하는지 이해하지 못하는 경우 문제를 적절하게 해결해야합니다. 그렇지 않으면 비즈니스 로직의 HTML이나 템플릿의 비즈니스 로직으로 끝납니다. 템플릿 엔진이 당신을 구할 수 없습니다. 개발자에게 기본 사항을 가르쳐야합니다.

그리고 개발자 그것을 이해한다면 템플릿 시스템은 한계 일뿐입니다. 개발 프로세스 어떤 가치도 추가하지 않고 새로운 구문을 배우고 다른 라이브러리를 최신 상태로 유지하며 실행 속도를 느리게하는 오버 헤드 만 추가 합니다 . 후자는 캐싱 등으로 해결할 수 있지만 그렇지 않으면 존재하지 않을 문제 만 해결합니다. 따라서 템플릿 시스템은 가치 나 이점을 전혀 제공하지 않습니다.

하지만 PHP가 아닌 템플릿 시스템을 사용하는 것이 합리적이라고 생각하는 한 가지 예외가 있습니다. 뷰 로직 프로그래머가 템플릿에 대한 액세스를 제한해야하는 경우입니다. 예를 들어, 블로그 호스팅 시스템의 제공 업체이고 사용자가 임의의 코드를 실행하지 않고도 템플릿을 개인화하고 코딩 할 수 있도록 허용하려는 경우입니다. 그러나이 주장 은 디자이너가 UI 프로그래밍을 돕기 위해 약간의 코드를 배우려는 경우에는 적용 되지 않습니다 . 스마티를 배울 수 있다면 반드시 PHP를 배울 수 있습니다 .


템플릿 시스템이 Smarty가 아닌 PHPTAL 을 사용하는 데는 여전히 좋은 이유가 있습니다 . PHPTAL 템플릿은 유효한 XML (따라서 XHTML) 파일입니다. PHPTAL에서 더미 콘텐츠를 더 많이 사용할 수 있으므로 표준 도구로 처리하고 테스트 할 수있는 최종 모양의 유효한 XHTML 파일을 얻을 수 있습니다. 다음은 작은 예입니다.

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr tal:repeat="users user">
      <td tal:content="user/first_name">Max</td>
      <td tal:content="user/last_name">Mustermann</td>
      <td tal:content="user/age">29</td>
    </tr>
  </tbody>
</table>

PHPTAL 템플릿 엔진은 사용자 배열의 모든 값을 자동으로 삽입하고 더미 값을 대체합니다. 그럼에도 불구하고 테이블은 선택한 브라우저에 표시 할 수있는 유효한 XHTML입니다.


저에게 템플릿 엔진의 큰 특징 중 하나는 캐시 레이어가 투명하다는 것입니다. 나는 오래 전에 smarty를 사용해 왔고 캐시 물건은 삶을 더 쉽게 만듭니다. 또한 스마트 한 디자인으로 자신 만의 캐시 기능을 사용할 수 있습니다. 제 경우에는 일부 페이지에서 템플릿 출력을 저장하기 위해 memcache 또는 디스크를 사용해야하는지 선택합니다.

반면에 사이트에 트래픽이 많고 현명하게 관리하고 잘 조정하는 방법을 모르면 템플릿 엔진이 사이트 킬러가 될 수 있습니다. 하지만 현명하게 사용하지 않아도 사이트가 죽을 수 있습니다.

flickr은 현재 smarty를 사용하고 있습니다. 그다지 나쁘지 않겠습니까?


PHP 템플릿 시스템입니다. 핵심은 스스로 논리와 프레젠테이션을 분리하도록하는 것입니다. Smarty 또는 이와 유사한 것을 사용하면 논리와 표현을 혼합하는 것이 약간 더 불편할뿐입니다. 스스로 분리 할 수 ​​없다면 템플릿 시스템을 사용해도 도움이되지 않습니다. 할 일은 추가 처리 능력을 소모하는 것입니다.

핵심은 프레젠테이션 코드의 값을 변경하지 않는 것입니다. 이를 위해 if / endif 구문을 사용하면 PHP 자체가 Smarty만큼 효과적이라고 생각합니다.

<?php if($some_test): ?>
   <em>Some text!</em>
<?php endif; ?>

주로 템플릿에 적용되는 "안전하지 않은"백엔드 로직을 피하려고합니다. 대부분의 경우 템플릿이 디자이너에게 전달되기 때문에 우리는 그들이 할 수있는 폐쇄 된 세트만을 제공하고자합니다.


PHP 파일의 모든 템플릿을 간단하게 표시 할 수있는 기능이 마음에 듭니다 (탐색 막대와 같은 공통 요소에 대해 서로 내부에 템플릿 조각을 포함). 예를 들어, 로그인 한 경우 일반적으로 일부 정보를 인쇄하는 페이지가 있고 그렇지 않은 경우 오류가 발생한다고 가정합니다. PHP를 사용하면 다음과 같이 작성할 수 있습니다.

if (loggedIn)
{
    // print lots of HTML here
}
else
{
    // print error message
}

Smarty에서는 다음과 같을 수 있습니다 (아마도 잘못된 구문을 용서하십시오. 오래되었습니다).

if (loggedIn)
{
    $smarty->bind("info", someObject);
    $smarty->display("info.template");
}
else
    $smarty->display("error.template");

정말 영리하다면 오류 템플릿 대신 로그인 페이지 템플릿을 표시 할 수도 있고, 선택적으로 사용자가 왜 그곳에 갔는지 설명하는 메시지와 함께 표시 할 수 있습니다. 그리고 내가 작성한 기술을 사용하고 로그인 상자 표시로 전환하기로 결정했다면 한 줄만 변경하면됩니다! 나에게 그것은 단지보기와 논리의 분리를 유지하는 것이 아니라 여러 곳에서보기의 공통 요소를 재사용하는 능력에 관한 것입니다.


코드 점화기와 같은 MVC 프레임 워크를 사용하는 것이 기쁩니다. 나는 '보기'에서 값이 표시되는 방식에만 관련된 PHP 코드를 고수하는 경향이 있음을 발견했습니다. 그 효과에 대한 뷰에서 사용할 수있는 서식 지정 함수 라이브러리가 있습니다. 코드 점화기의 전제 중 하나는 템플릿 언어가 사용자를 제한하는 방식과 속도 저하로 인해 템플릿 언어를 사용하지 않는 것입니다.

I find that is better for designers to learn some PHP, so that they can achieve what they need to do eg. alternating class names. It will also make them more useful in the long term and it's not a huge leap from one syntax to the other.


You forgot htmlspecialchars() twice. That's why you need templating system.

Smarty is poor. Don't judge templating systems based on that.


Your analysis is reasonable. I suppose:

  • Template designers and back-end programmers may not be one in the same, so it promotes separation.
  • It protects you from yourself somewhat in that you can't really do "too much" PHP in your templates.
  • It may be easier to optimise/precompile templates in some scenarios? (This is speculation)

Personally, I think they're more hassle than they're worth. Particularly they don't work if you want to hand the templates to "designers" since the WYSIWYG tools don't know what to do with them.


One template engine advantage that I didn't see was the possibility of dynamic html elements - something like asp.net controls. For example, with PEAR's HTML Template Flexy you can have dynamic form elements that automatically maintain state. A regular html select element can be populated and have the selected item set in the code behind without loops or conditionals in the template.


I think that cleaner syntax is quite a big win. Although it may look like only a few characters, but when you do it every day, then each character starts to count.

And {$myvar|escape} is IMHO quite a bit shorter than <?php echo htmlspecialchars($myvar); ?>. (Keeping in mind that <?=$foo?> syntax is only available when it is specially enabled in PHP conf.)


I don't think you should use a template engine. Instead you should use something like Zend_View which encourages you to do separate logic from presentation, but allows you to build your presentation layer in PHP.


  • You want to use a file with PHP code as a template? Fine.
  • You want to use your variables in said template? Fine.

Just remember to separate logic and final output (presentation). This is better accomplished with a templating framework. But you dont have to learn something like Smarty.

  • If you use Zend_View or similar you can use PHP code all the way.

Many people here have the correct reply. Smarty is not templating in PHP. Far from it. Smarty is there mostly for those who have to use designers (ie non-programmers) to edit and setup the display of pages. If everyone who are gonna change the layout of your pages can program, you can go with a more PHP code oriented templating system. But you really should have all your output data ready and send it to the template. If you let each page fetch, process and display the content, you will have to refactor it sooner then later.


When you're writing code for someone else. For example, I was once involved in the creation of a rigid web application framework that should be customizable for our customers. One important request was that the customer could hire a designer to modify the templates without having to be able to program. Even more important, he might not be authorized to change the code.

Smarty for example allows to implement quite rigid restrictions on what the template may do. Basically, our application disabled all but the most basic code constructs and a selected set of modifier functions. So we had two goals that were served well by a template engine: simplicity and security.


And let us not forget the future. Websites are old almost the minute they are published. You WILL need to update the look and feel at some point. If you maintain separation often times a designer alone can complete a whole new website with the same programming on the back end. This allows for faster and cheaper redesigns, allowing you to only involve the programmer if new functionality is required.


Some might argue that Smarty does what PHP can do already: separate the presentation from business logic. The PHP programming language is great for code development but when mixed with HTML, the syntax of PHP statements can be a mess to manage. Smarty makes up for this by insulating PHP from the presentation with a much simpler tag-based syntax. The tags reveal application content, enforcing a clean separation from PHP (application) code. No PHP knowledge is required to manage Smarty templates.

The importance of this separation is situational. It is commonly more important to web designers than it is to PHP developers. Therefore, Smarty is commonly a good fit when the roles of developers and designers are separated. There is no right or wrong answer: every development team has their own preferences for managing code and templates. Aside from a clean tag-based syntax, Smarty also offers a wide variety of tools to manage presentation: granular data caching, template inheritance and functional sandboxing to name a few. Business requirements and the PHP code Smarty is being used with will play a large role in determining if Smarty is a good fit.


I'd wager that if a PHP template language was so coercive as to force you to use it, you wouldn't use it at all. The ability to 'jump out' and do things your way when in trouble is one of the attractives of PHP.

I don't say that it's a good thing, nor that the code will be maintainable, just that in the initial considerations, I wouldn't choose a template language that blocked me completely.

Otherwise, I agree that templating systems help you divide work between coding and design, and possibly letting designers design and the coding to us.


I personally always use templating engines in php, python or whatever.

The first obvious reason already mentioned by others:

It's forces you to not use any business logic in your templates.

Yeah sure, discipline would do just fine, when you have it.

But this is just a tiny aspect of why you would use a templating engine. Most of them are more than just an engine and could be considered templating frameworks, whether you like it or not.

For example, Smarty also has advanced caching features like partial caching. Really useful stuff, things you would have todo all by yourself when using just php as templating language.

And please do not forget all those really useful helper functions just a quick search away in the docs. Most of them also provide an easy way to plugin your own functions and/or toolkit.

So yes, it's a matter of choice. When in need for really simple templating, consider showing some discipline a keep your logic out of your templates. But when you expect your application to grow, you will eventually be in need of template framework's features. And by then, you hopefully not reinventing the wheel by coding it all yourslef.

And last but not least, for me there is one killer feature available in some templating frameworks.

Template Inheritance

I've came to know it from Django and i'm now using it in the latest Smarty 3. The guys from the Symphony framework also have Twig, which you can consider a port with the Django syntax.

It's look a bit strange at first, but is extremely powerful. You build your skeleton and define various blocks. You can extend such skeleton and fill in (override) the blocks with your content.

For me that's a keeper!


template management system, we can manage the template files separately. system execution time will be faster then normal PHP project. so here PHP files and template files are separately maintained.

once run the files the code will be saved it template_c. so its not compile many times.


I several times used tinybutstrong, which has a pretty neat and simple syntax. No loops or pseudocode in the html template.

From their homepage:

TinyButStrong is a library that enables you to dynamically create XML/HTML pages and any other files based on text source. It's a Template Engine for the PHP language. It enables you to easily display information from your database, but also to seriously harmonize and simplify your PHP programming.

TinyButStrong is oriented to HTML but not specialized to Html. This means it can work as well with Text files, XML, RSS, RTF, WML, Excel (xml), ... The OpenTBS plug-in enables your to merge OpenOffice and Ms Office documents.


Developers who will make use of OOPs concepts heavily,like JAVA/Spring/Oracle PL-SQL people,they say that PHP language itself is used for presentation/view/display logic in the Enterprise level projects. In these BIG projects the backend is Oracle,the database is fetched using pl-slq/java and presentation is php.The best example is facebook.http://en.wikipedia.org/wiki/Facebook facebook uses php for presentation, java/c++ as backend interface.

The only reason php is used as presentation because it works closely with HTML,but java/c++ is more OOPs based and can't be fit directly with HTML. Tell me one CMS(joomla/drupal/wordpress) or framework(zend/symfony/Yii) which makes use of Smarty? So WHY smarty is necessary?


I like using templates for a couple of reasons:

1) It cleans up the readability of the PHP code. My PHP files become bloated and ungraceful when there are print("") statements with chunks of HTML everywhere. Also, issues crop up like how do you pass variables into the HTML text? Do you use tags everywhere? Do you use print("") and escape your HTML quotes and concatenate your variables? Do you use print("") and use single quotes in HTML, going against the standard, and insert your variables directly?

2) It cleans up the presentation of the HTML code. It can become hard to keep your generated HTML looking good if it is cut and hacked to pieces across multiple files. For example, your indenting can get way off.

3) It allows you to create multiple templates, and then a logged in user can select which template/skin he wants to display when browsing your website, and you can also quickly and effortlessly change the default template to something else if you're so inclined.

Overall, it's just a better way of organizing everything. There is a little bit of tradeoff in having to learn and type template class commands, open multiple files, etc. But in my opinion I think it is worth it because the code's readability and organization goes up.

참고URL : https://stackoverflow.com/questions/436014/why-should-i-use-templating-system-in-php

반응형