Базовая инсталяция

Инсталируйте библиотечный файлы Smarty, которые анаходятся в папке /libs/ дистрибутива. Вы НЕ ДОЛЖНЫ редактировать эти файлы. Они разделены среди всех приложений и могут изменяться только при обновлении Smarty.

Пример 2-1. Бибилотечные файлы Smarty

Smarty.class.php
Smarty_Compiler.class.php
Config_File.class.php
debug.tpl
/plugins/*.php (все файлы!)

Smarty использует PHP константу SMARTY_DIR, которая указывает путь к библиотечным файлам Smarty. Обычно, если приложение может найти файл Smarty.class.php , то нет необходимости устанавливать SMARTY_DIR, Иначе, если Smarty.class.php не в вашем include_path, или вы не указывали абсолютный путь к нему в приложении, то вы должны определить SMARTY_DIR вручную. SMARTY_DIR должен включать завершающий слэш.

Как надо создавать обект Smarty в ваших PHP сценариях:

Пример 2-2. Создание обекта Smarty

require('Smarty.class.php');
$smarty = new Smarty;

Попробуйте выполнить вышеупомянутый сценарий. Если Вы получаете ошибку о том, что Smarty.class.php не найден, вы должны селать одно из следующего:

Пример 2-3. Укажите абсолютный путь к библиотечному каталогу

require('/usr/local/lib/php/Smarty/Smarty.class.php');
$smarty = new Smarty;

Пример 2-4. Добавьте библиотечный каталог к php_include пути

// Отредактируйте ваш php.ini файл, добавьте библиотечный 
// каталог Smarty к include_path и перезаупстите веб сервер.
// Тогда следующее должно работать:
require('Smarty.class.php');
$smarty = new Smarty;

Пример 2-5. Установите SMARTY_DIR константу вручную

define('SMARTY_DIR','/usr/local/lib/php/Smarty/');
require(SMARTY_DIR.'Smarty.class.php');
$smarty = new Smarty;

Теперь, когда библиотечные файлы находятся на месте, пришло время установка каталоги Smarty для вашего приложения. Smarty требует четыре каталога, которые (по умолчанию) называются templates , templates_c , configs и cache . Каждый из них определяем свойствами класса Smarty $template_dir , $compile_dir , $config_dir , и $cache_dir соответственно. Очень рекомендуется, чтобы вы устанавливали отдельные наборы этих каталогов для каждого приложения, которое будет использовать Smarty.

Убедитесь, что Вы знаете расположение вашего корня документа на веб сервере. В нашем примере, корень документа - "/web/www.mydomain.com/docs/". К каталогам Smarty обращается только библиотека Смарти и никогда не обращает непосредственно web-браузером. Поэтому, чтобы избежать любых предприятий(беспокойств) защиты, рекомендует разместить эти каталоги в каталог от корня документа. Be sure you know the location of your web server document root. In our example, the document root is "/web/www.mydomain.com/docs/". The Smarty directories are only accessed by the Smarty library and never accessed directly by the web browser. Therefore to avoid any security concerns, it is recommended to place these directories in a directory off the document root.

For our installation example, we will be setting up the Smarty environment for a guest book application. We picked an application only for the purpose of a directory naming convention. You can use the same environment for any application, just replace "guestbook" with the name of your app. We'll place our Smarty directories under "/web/www.mydomain.com/smarty/guestbook/".

You will need as least one file under your document root, and that is the script accessed by the web browser. We will call our script "index.php", and place it in a subdirectory under the document root called "/guestbook/". It is convenient to setup the web server so that "index.php" can be identified as the default directory index, so if you access "http://www.mydomain.com/guestbook/", the index.php script will be executed without "index.php" in the URL. In Apache you can set this up by adding "index.php" onto the end of your DirectoryIndex setting (separate each entry with a space.)

Lets take a look at the file structure so far:

Пример 2-6. Example file structure

/usr/local/lib/php/Smarty/Smarty.class.php
/usr/local/lib/php/Smarty/Smarty_Compiler.class.php
/usr/local/lib/php/Smarty/Config_File.class.php
/usr/local/lib/php/Smarty/debug.tpl
/usr/local/lib/php/Smarty/plugins/*.php

/web/www.mydomain.com/smarty/guestbook/templates/
/web/www.mydomain.com/smarty/guestbook/templates_c/
/web/www.mydomain.com/smarty/guestbook/configs/
/web/www.mydomain.com/smarty/guestbook/cache/

/web/www.mydomain.com/docs/guestbook/index.php

Smarty will need write access to the $compile_dir and $cache_dir , so be sure the web server user can write to them. This is usually user "nobody" and group "nobody". For OS X users, the default is user "www" and group "www". If you are using Apache, you can look in your httpd.conf file (usually in "/usr/local/apache/conf/") to see what user and group are being used.

Пример 2-7. Setting file permissions

chown nobody:nobody /web/www.mydomain.com/smarty/guestbook/templates_c/
chmod 770 /web/www.mydomain.com/smarty/guestbook/templates_c/

chown nobody:nobody /web/www.mydomain.com/smarty/guestbook/cache/
chmod 770 /web/www.mydomain.com/smarty/guestbook/cache/

Technical Note: chmod 770 will be fairly tight security, it only allows user "nobody" and group "nobody" read/write access to the directories. If you would like to open up read access to anyone (mostly for your own convenience of viewing these files), you can use 775 instead.

We need to create the index.tpl file that Smarty will load. This will be located in your $template_dir.

Пример 2-8. Editing /web/www.mydomain.com/smarty/guestbook/templates/index.tpl

{* Smarty *}

Hello, {$name}!

Technical Note: {* Smarty *} is a template comment. It is not required, but it is good practice to start all your template files with this comment. It makes the file easy to recognize regardless of the file extension. For example, text editors could recognize the file and turn on special syntax highlighting.

Now lets edit index.php. We'll create an instance of Smarty, assign a template variable and display the index.tpl file. In our example environment, "/usr/local/lib/php/Smarty" is in our include_path. Be sure you do the same, or use absolute paths.

Пример 2-9. Editing /web/www.mydomain.com/docs/guestbook/index.php

// load Smarty library
require('Smarty.class.php');

$smarty = new Smarty;

$smarty->template_dir = '/web/www.mydomain.com/smarty/guestbook/templates/';
$smarty->compile_dir = '/web/www.mydomain.com/smarty/guestbook/templates_c/';
$smarty->config_dir = '/web/www.mydomain.com/smarty/guestbook/configs/';
$smarty->cache_dir = '/web/www.mydomain.com/smarty/guestbook/cache/';

$smarty->assign('name','Ned');

$smarty->display('index.tpl');

Technical Note: In our example, we are setting absolute paths to all of the Smarty directories. If '/web/www.mydomain.com/smarty/guestbook/' is within your PHP include_path, then these settings are not necessary. However, it is more efficient and (from experience) less error-prone to set them to absolute paths. This ensures that Smarty is getting files from the directories you intended.

Now load the index.php file from your web browser. You should see "Hello, Ned!"

You have completed the basic setup for Smarty!