Introduction

This chapter touches upon general issues concerning the structure and functioning of Components 2.0. It gives an insight of the basic principles, terminology, general structure of components and their physical location and functioning in the context of the system.

Basic principles

Introducing Components

Components are blocks that build the site public section. They allow to reuse the existing, once written and debugged code on the same or different sites. The Bitrix Site Manager environment visual tools provide tools to add and configure the component parameters without having to create any task specific code. The Bitrix standard components are regularly updated, adding new functions and fixing possible errors.

Main Features of Components 2.0

The conceptual difference between the components 2.0 and 1.0 is that the components 2.0 separate the view from the business logic. More than one view can be created for a single logic unit. Views can include those depending on a current site template. A view (presentation template) can be created in any template language that can be used with PHP. For example: PHP, Smarty, XSL etc. There is no need to modify the component logic to modify the view. This has made the information view configuration much easier: a developer does not need to look deep into the component logic. The view template is much simpler than the component as a whole. The logic is a component, the view is a template of the component view.

Physically, the components are located in a single centralized storage (folder). This makes the site structure more integrate and comprehensive. The folder is available for read operations, which means that a component and its templates can easily use their additional resources.

Note! Files that cannot be accessed directly must start with the following code:
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>

A component keeps the private data in a private folder. That is why they can be easily shared between projects.

Important: components are atomic units.

Types of Components

Components can be simple (single page) or composite (multi-page). Though the simple and compound components are rather similar in their structure and the activation method, they are completely different in logic.

Simple Components

Simple (single page) components create an area on a page surface. They come at hand when you need to render data from different modules on a single page (for example: blogs and information blocks) or data from different information blocks (news and commercial catalog). Evidently, simple components are not convenient to create a whole news section or a catalog because this requires the creation of a considerable number of pages and controlling their linkage.

Let us consider an example of creating a news section using simple components. Create, for example, a news index page index.php and add the News list (bitrix:news.list) component. This component displays a news title, preview text and other media depending on the component settings. Each element in the news list is a link to an individual news details page (for example: detail.php). Add the News detail (bitrix:news.detail) component to the details page:

Click on image to enlarge Click on image to enlarge

The News list component's input parameters should be configured in such a way that it could build links to the news details page (with the news ID). For this, specify a path to this page and the name of a parameter that will be used to pass the news ID:

In this case, the detail.php page and the news index page should be in the same folder.

In the News detail component, configure the parameters so that it could build a link to the news index page:

Additionally, specify the PHP code that will evaluate to the news ID:

Now, if the parameters of the components are configured properly, we should have the following result in the public section:

Click on image to enlarge Click on image to enlarge

Composite Components

Composite (compound, multi-page) components create the site sections. For example, the commercial catalog component creates the whole catalog section including the catalogs page, the groups page and the product pages. Essentially, a composite component is a set of pages from the visitor's point of view, but represented by a single page physically. The foundation of composite components are simple components and the use of the single-page logic.

The advantage of composite components is the automatic preparation of parameters of the underlying simple components: you do not have to care about the interrelationships of internal parameters.

Composite components resolve the following problems:

  • Avoid the creation of numerous pages to add all required sub-components to them. There is no need to configure common parameters of each individual component.
  • Avoid the need to establish composite associations between sub-components. For example, you do not have to configure the link creation rules etc.
  • Components (even those driven by custom view templates) can be enriched with new pages. For example, if you add page (sub-component) showing 10 most rated forum visitors, this page becomes momentarily available in the public section.
  • The component view template can be changed at one stroke instead of configuring each of the underlying sub-components.

A typical composite component workflow is as follows:

  • the component takes user actions on input and defines the exact page to show to a visitor and attaches an appropriate template to the page;
  • the page template attaches simple components and configures their parameters as required;
  • the simple components perform the requested operations: request data from the system kernel, format and display data to the visitor; show various controls (links, forms, buttons etc.);
  • the visitor sends a new request to the composite component using the controls.

A simple example of a composite component is the News (bitrix:news) component. The only required actions are add this component can be added to a page and configure its parameters.

Hence, the creation of a news section requires only one physical page but creates as many "virtual" pages as required. For example, the news index page:

Click on image to enlarge

the news details page:

Click on image to enlarge

Physical Location. Naming Convention

Physical location of components

All components are stored in the /bitrix/components/ folder. The system components are in the /bitrix/components/bitrix/ folder. The content of this folder is updated by the update system and must not be modified by users.

Note! Modifying the system component folder /bitrix/components/bitrix/ can have unpredictable effects.

Users can store their own components in any subfolder of /bitrix/components/, or in the /bitrix/components/ root.

Naming convention

The name of a subfolder in /bitrix/components/ is the component namespace. For example, all system components belong to the bitrix namespace. When creating a custom component, you should create a namespace and put custom components there.

For example, a system component news exists located in the bitrix namespace. If you need a custom news component implementing functions unavailable in the standard system component, you should create a namespace (subfolder) in /bitrix/components/ (for example, demo) and put the custom component news there. The two components news will be available in different namespaces: bitrix:news and demo:news; both of them will be shown in the component tree in the visual editor.

   

The component names have the format identifier1.identifier2.... For example: catalog, catalog.element, catalog.section.list etc. A good idea is to create hierarchical names, from common to particular, e.g. catalog.section.elements for a component that would display a list of products of a certain group. Global components (that reside out of namespace) do not specify the namespace.

Structure of the Component Folder

The component folder can contain the following subfolders and files:

  • subfolder help that contains component help files. This folder contains subfolders named by the language abbreviation. Each language folder must have a file index.php, which is the main help file for the corresponding language. For example, the path name of the english help file can be /help/en/index.php. The help files should describe the structure of an array in which the component returns data to the template. The subfolder help is optional.
  • subfolder install that contains installation and uninstallation scripts. The installation script name is install.php, and the uninstallation script is uninstall.php. The subfolder install is optional.
  • subfolder lang containing component messages. The subfolder names are the abbreviations of languages in which the text messages are stored. A good practice is to save a text message file under the same name as a corresponding file of the component, and store it in the same folder hierarchy. For example, the file with english messages for /install/uninstall.php is to be saved in /lang/en/install/uninstall.php. The lang folder is optional if the component does not use language-dependent messages.
  • subfolder templates in which the component view templates are stored. The subfolder templates is optional if the component has no view templates.
  • file component.php containing the component logic. This file must exist.
  • file .description.php, which contains the name and the description of the component. Additionally, it describes the component disposition in the visual editor component pane. This file must exist.
  • file .parameters.php, which contains the description of the component input parameters for the visual editor. This file must exist if the component uses input parameters.
  • any other folders and files containing the resources required by the component, for example: the folder images.

Managing the Component Parameters

In this section we shall study the usage of components: placement, configuration, managing parameters from the public section and Control Panel.

Component Bar in the Visual Editor

A special user interface has been developed based on the visual HTML editor to allow users quickly add components to their pages:

Click on image to enlarge

All visual components are shown on a special component bar. The bar configuration depends on the visual editor settings (opens the settings form ).

To customize the bar visibility, open the Visual editor settings form, click the Taskbar tab and check the bars that are to be shown in the editor window:

Click on image to enlarge

The Components 2.0 tab contains new components. They are grouped by functions (Content, Service, Communication, e-Store, Utilities) and can be unfold to find components.

   
If a system component is copied in another folder (for example: /bitrix/components/demo/), by default they are shown in the same section as the system components. They differ only by the namespace.    
As an example, the demo site shows the custom components of the demo namespace (stored in /bitrix/components/demo/) in the My components folder. Each of them has the .description.php file modified in such a way that the components are displayed in a separate folder.

Adding and Configuring Components in the Visual Editor

When creating/editing a page using the HTML editor, you can select the required component and drag-drop it to the page body:

Click on image to enlarge

When a user selects a component in the page body, the Properties panel shows the parameters of a selected component:

Click on image to enlarge

For more convenient configuration, the component parameters are divided in groups. For example: General parameters, RSS Settings etc. The number of groups and their content depends on a certain component.

Beside the fields, you will find the icons . They display help tips when the mouse pointer hovers over an icon:

Click on image to enlarge

Some drop-down fields allow selecting the value (other)–>. This requires that you enter a value (PHP code) in the next field:

Furthermore, the component parameters can be configured by editing the page source code. The button in the HTML editor opens the source code editor:

Click on image to enlarge

Useful information:
  • If a page contains more than one component that set the page title, only the last title set is effective.
  • If a page contains more than one component that add buttons to the Control Panel toolbar, uncheck the Display panel buttons for this component option box in the component settings. This will help to avoid overloading the user interface.
  • Only the site administrators can manage visual components. This restriction is imposed to make site management more secure because visual components use PHP calls.

Managing Components in Site Design Mode

When you switch to site design mode (the Design tab), all components embedded in a page show a special component control button:

Click on image to enlarge

Note that a composite component shows multiple buttons:

Click on image to enlarge

This reason for such a layout is the composite component architecture. The topmost button controls the component core. Other buttons serve to control the simple subcomponents that comprise the composite component.

Clicking the component control button invokes a menu containing the component management commands:

A typical menu contains the following commands:

– edits the component parameters. This command is always available for any component except subcomponents in a composite component. When clicked, this command shows a properties form in which you can edit the component parameters without having to open a page in the editor.

– copies the component template. This command is always available. Shows a dialog window to specify the component template name and to which destination site template the template is to be copied.

– edits the template page. This command is available if the component uses a custom template.

– edits a template CSS file. This command is available if the component uses a custom template.

– clears the component cache.

Other commands are component dependent. For example, the following menu control commands may exist:

– edits menu items.
– creates a menu in a current section.

If a component renders information stored in an information block, the menu can have the following commands:

– adds an information block element, e.g. news, article, product etc.
– adds an information block section.

Virtually any web site shows advertisement or uses web forms. To help manage these web site entities, the following commands exist:

for advertisement banners:

– edits a current banner.
– shows a filtered list of banners.

for web forms:

– edits a web form template.
– edits the web form parameters.

Configuring the Component Parameters in Site Design Mode

You can manage the parameters of components on your pages directly from the site public section: authorize and click the Design tab. Then, to invoke the component properties form:

  1. click the component control button and select the command Edit component parameters,
  2. or
  3. click Components on the Control Panel toolbar and select the required component from the dropdown menu:



    Note: the order of items in this menu reflects the order of components on a page.

The following form will open:

Click on image to enlarge

The form is similar to the Properties bar in the visual editor. The Save button applies the changes made.

Component Templates

This chapter describes the component template structure; methods to create and edit component templates.

Basic Principles

The two types of component templates exist: system and custom:

  • System templates are shipped with the standard components and stored in the templates subfolder of a component folder.
  • Custom templates are those modified to deliver the required functions to a certain site. They are to be located in the site template folders (i.e. in /bitrix/templates/site_template/). Copying a component template using the system tools saves it in the folder: /bitrix/templates/site_template/components/namespace/component_name/template_name.

A component template is identified by the name. By default, templates have the name .default. If a template name is not specified, the default template is attached. Other templates can have arbitrary names.

The component templates can be represented by folders or files. If a template is a single file requiring no language dependent messages, certain styles or other resources, this template can be stored in a single file. Otherwise, templates should be stored in a folder.

A component template is atomic, i.e. it is an indivisible unit. If you need to customize a system template for a certain site, copy it to the site template folder.

For example, the bitrix:catalog.site.selector component has a dropdown system template located in the templates subfolder of the component folder:

If this component template requires customization, copy the folder of the dropdown template to /bitrix/templates/site_template/components/bitrix/catalog.site.selector/ and modify it there as required.

The Simple Component Template Structure

The simple component template folder can contain the following folders and subfolders:

  • The subfolder lang containing component language-dependent messages in nested subfolders. The subfolder names are the abbreviations of languages in which the text messages are stored. A good practice is to save a text message file under the same name as a corresponding file of the component, and store it in the same folder hierarchy. For example, the file with English messages for /install/uninstall.php is to be saved in /lang/en/install/uninstall.php. The lang folder is optional if the component does not use language-dependent messages.
  • The file result_modifier.php. It is included immediately before the inclusion of a component template. This file takes the component results as an array $arResult, and the component input array $arParams. This allows to change the contents of $arResult as required. Imagine a system component that does everything you need but does not return some important field. A straightforward solution is to develop a custom component. But this approach is time and resource consuming, and the component will not be updated via the update system. Instead, you can create a file result_modifier.php in the component template and add a missing field to $arResult. This file (result_modifier.php) is optional.
  • The file style.css with the styles required by the template. The file is applied if a template requires custom styles. The style.css file is included automatically if it exists in the template folder. This file is optional.
  • The file script.js which defines JavaScript required by the template. This file is included in HTML by adding <script src=".../script.js" type="text/javascript"></script>. The script.js file is included automatically if it exists in the template folder. This file is optional.
  • The file .description.php containing the template name and description for the editor. For example, the Menu (bitrix:menu) component has this file defining the template name and description in the component parameters. The .description.php file is optional.
  • The file .parameters.php containing the description of the template input parameters for the editor. For example, the News List (bitrix:news.list) component template had this file defining the template settings in the component parameters (element date, element name etc.). This file is optional.
  • The file template.ext, which is the template itself. The .ext extension depends on the template engine used. The default extension is .php. This file must exist.
  • Any other folders and files containing the resources required by the component, for example: the folder images containing the template images.

The Structure of A Composite Component Theme

Composite components have been extended with the concept of themes. This concept is similar to the one of a single page template, but as long as the composite components include logics and templates of single page components, the concept of themes is composite. A theme folder of the composite components can contain the following subfolders and files:

  • Subfolder lang containing language-dependent messages. The subfolder names are the abbreviations of languages in which the text messages are stored. As with the component messages, it is a good practice to save a text message file under the same name as a corresponding template file, and store it in the same hierarchy relative to the /lang/language_code/ folder. For example, the file with english messages for /section.php is to be saved in /lang/en/section.php. The lang folder is optional if the component does not use language-dependent messages.
  • The file result_modifier.php. It is included immediately before the inclusion of a component template. This file takes the component results as an array $arResult, and the component input array $arParams. This allows to change the contents of $arResult as required.
  • The file style.css that defines styles required by the template. The file is applied if a template requires custom styles. The style.css file is included automatically if it exists in the template folder. This file is optional.
  • The file script.js which defines JavaScript required by the template. This file is included in HTML by adding <script src=".../script.js" type="text/javascript"></script>. The script.js file is included automatically if it exists in the template folder. This file is optional.
  • The file .description.php containing the theme name and description for the editor. This file is optional.
  • The file .parameters.php containing the description of the template input parameters for the editor. This file can exist in themes of components that define user-editable template options. This file is optional.
  • Files page_name.ext that are templates of pages of composite components. The .ext extension depends on the template engine. The default extension is .php. Files page_name.ext must exist for each page of a composite component.
  • Templates of simple components which are the constituent parts of composite components. These templates are located in folders /namespace/simple_component_name/ relative to the composite component template folder.
  • Any other folders and files containing the resources required by the component, for example: the folder images containing the images required by the template.
  • Simple components that are parts of composite components are included in templates of composite components pages.

Editing The Templates

If you need to customize a system component template, copy it entirely to a site template folder and then edit the copy.

Editing A Simple Component Template

To edit a component template, copy the system component template to a site template folder. The system provides the convenient user interface to copy a component template to a required site template, edit the template and apply it.

To copy the template, switch to site design mode by clicking the Design tab. Click the component control button and select the command: Copy component template. This will open the template copying form:

Click on image to enlarge

Specify here the name for a new component (otherwise, the system will offer a default name). You also have to select the site template to which the template will be copied.

If the option Apply new component template is active, the new template will be applied to the component, and the component management menu will contain the following commands:

- edits the template;
- edits the template CSS file.

If you uncheck this option, you can apply the new template when editing the component parameters.

If the option Edit template is checked, the component template will be opened for editing. Otherwise, you can edit it later in Site Explorer or by clicking Edit component template:

Click on image to enlarge

Editing the Composite Component Template

The composite components support themes. The concept of theme includes:

  • All templates of single page components as a part of a composite component.

    For example, the following single page component templates comprise the News (bitrix:news) composite component theme:
    • Filter by elements (bitrix:catalog.filter);
    • Topic (comments) (bitrix:forum.topic.reviews);
    • Vote (bitrix:iblock.vote);
    • News details (bitrix:news.detail);
    • All news (bitrix:news.index);
    • News list (bitrix:news.list);
    • News RSS (export) (bitrix:rss.out);
    • Search form (bitrix:search.form);
    • Search page (bitrix:search.page);
  • Page templates used by a composite component. A theme includes files that define the layout of subcomponents on a page.

    For example, the news page shows the following items: a filter, a search form, an RSS feed link, the news headlines. The component layout definition file is news.php.
  • CSS files style.css and other theme elements. For more detailed information on the theme structure, see the Composite component theme structure lesson.

To edit the composite component theme, switch to the Design mode. The page will show the component control buttons. The topmost button controls the component core. Other buttons serve to control the simple subcomponents that comprise the composite component.

Click the component core control button and select Copy component template in the menu. This command copies the component theme to a site template of your choice. You will have to provide the copy parameters in a dialog window:

Click on image to enlarge

Click Save. The whole theme will be copied to the specified site template.

Click on image to enlarge

As you can see, the folder template1 contains the duplicated theme. Now you can edit the template by selecting the command Edit component template in the component control menu, or copy the theme again by selecting Copy component template.

If a composite component uses a custom template, the subcomponent control menus are slightly different:

  • Edit component template – edits the template of a current subcomponent;
  • Edit template CSS-file – opens the CSS definitions for editing.
Note! You cannot edit the composite component theme as a single entity. Since composite components consist of different simple components, you have to edit them individually.

Developing Components

In this section, we shall consider the basic aspects of the component development: inclusion of a component and its elements; redefinition of variables and activation of the template engines; component caching.

Including Components

The following command connects a component to a page:

$APPLICATION->IncludeComponent($componentName, $componentTemplate, 
        $arParams = array(), $component = null)

here:
$componentName – the full name of a component to be added;
$componentTemplate – the component template;
$arParams – an array of the component input parameters;
$component – a component instance. Used if a component is connected from a composite component template which defines the $component variable.

Consider the following examples of using the components.

1. Connect the bitrix:catalog component with the default template:

$APPLICATION->IncludeComponent("bitrix:catalog","", 
    array( 
         "SEF_MODE" => "Y",  
         "SEF_FOLDER" => "/catalog/",  
         "IBLOCK_TYPE_ID" => "catalog",  
         ) 
);

2. Connect the bitrix:catalog.list component of a composite component template applying the table/index.php template:

$APPLICATION->IncludeComponent("bitrix:catalog.list","table/index.php", 
    array( 
         "IBLOCK_TYPE_ID" => "catalog",
         ), 
    $component 
);

The following predefined variables are available inside a component:

$componentName – the component full name;
$componentTemplate – a template to be applied to a component;
$arParams – the component input parameters (i.e. parameters passed to a component). The parameters are also available by their names;
$componentPath – the path to a component relative to the site root;
$parentComponentName – the parent component name (empty if a component is orphan);
$parentComponentPath – the path to a parent component relative to the site root (empty if a component is orphan).
Besides, a component can access the $APPLICATION, $USER, $DB global variables.

Structure of a Typical Component

A generic component declaration

<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?> 
<?
 // Verify and initialize input parameters
 if (the cache contains valid component output) 
 { 
 // Render cached data
 } 
 else 
 { 
 // Query data and create $arResult array according to structure
 // described in the component help
 $this->IncludeComponentTemplate(); 
 // Cache output here
 } 
?>

Adding a component language message file

The system automatically includes the language message files for a component and all the standard files (component.php, .description.php, .parameters.php). In other files that exist in a component, you can include language message files using the following call:

$this->IncludeComponentLang($relativePath = "", $lang = False)

here:
$relativePath – the path to a file relative to the component folder;
$lang – the language. A special value of False specifies the current language.

Example:

   $this->IncludeComponentLang("myfile.php");


Applying a component template

A template can be connected using the call:

$this->IncludeComponentTemplate($templatePage = "");

here, $templatePage is a current page name for a composite component, or an empty string for a simple component.

The following examples illustrate the inclusion of a component template:

1. Include the template of a current composite component for the section page:

   $this->IncludeComponentTemplate("section");

2. Include the template of a current simple component:

   $this->IncludeComponentTemplate();

Inside the component, the following predefined variables are available:

$templateFile – the path to the template relative to the site root;
$arResult – an array of the component return values;
$arParams – an array of the component input parameters;
$arLangMessages – an array of the template language dependent messages (undefined for PHP templates);
$templateFolder – the template folder, if the template resides in a folder (that contains additional resources);
$parentTemplateFolder – the parent template folder;
$component – the current component instance.

A PHP template can access the $APPLICATION, $USER, $DB global variables.


Additional methods available in components and templates

string CComponentEngine::MakePathFromTemplate($pageTemplate, $arParams);

here:
$pageTemplate – a page template in the following format: /catalog/#IBLOCK_ID#/section/#SECTION_ID#.php or catalog.php?BID=#IBLOCK_ID#&SID=#SECTION_ID#;
$arParams – an associated parameter mapping array. Here, keys are the parameter names and values are the parameter value.

Returns the path based on the $pageTemplate path template and the mapping array.

Example:

$url = CComponentEngine::MakePathFromTemplate(
"/catalog/#IBLOCK_ID#/section/#SECTION_ID#.php", 
        array( 
             "IBLOCK_ID" => 21, 
             "SECTION_ID" => 452  
             ) 
);

Establishing explicit links between subcomponents in a composite component

You can link the subcomponents using the return values and input parameters of the components.

If you need to pass data from a component comp1 to comp2, add the following instruction to the end of the component comp1 code:
return data;

Connect the component comp1 in the following way:

$result = $APPLICATION->IncludeComponent(comp1, ...);

Now, the data are in the $result variable and they can be passed to the comp2 component as input parameters.

Variable redefinition and custom template engines

Redefining input variables

Each component has a set of variables to accept the input data. For example, the bitrix:catalog.section component has the variables IBLOCK_ID and SECTION_ID in which the catalog and product group ID's are passed.

All components of which a composite component consists should follow the uniform variable naming rules. For example: the bitrix:catalog component and all its subcomponents (bitrix:catalog.list, bitrix:catalog.section etc.) use variables IBLOCK_ID, SECTION_ID, ELEMENT_ID etc.

Use the parameter VARIABLE_ALIASES if you want to redefine the variables of a composite component you add to a page.

In SEF mode, this parameter must be in the following format:

"VARIABLE_ALIASES" => array( 
      "list" => array(),
      "section" => array(
                        "IBLOCK_ID" => "BID",
                        "SECTION_ID" => "ID"
                        ),
                        "element" => array(
                        "SECTION_ID" => "SID",
                        "ELEMENT_ID" => "ID"
                        ),
)

Here, the array keys mirror those existing in a path template array. Variables can be redefined for each path individually.

In non-SEF mode, this parameter has the following format:

"VARIABLE_ALIASES" => array(
                           "IBLOCK_ID" => "BID",
                           "SECTION_ID" => "GID",
                           "ELEMENT_ID" => "ID",
)

Example 1:

Assume that we want to have the bitrix:catalog component in /fld/cat.php handle the following paths:

/catalog/index.php – for catalog index;
/catalog/section/group_code.php?ID=catalog_code – for product groups;
/catalog/element/product_code.php?ID=group_code – for detailed information about a product.

Specify the following assignments in the component input parameters:

"SEF_MODE" => "Y",    
"SEF_FOLDER" => "/catalog/",
"SEF_URL_TEMPLATES" => array(
                    "list" => "index.php",
                    "section" => "section/#SECTION_ID#.php?ID=#IBLOCK_ID#",
                    "element" => "element/#ELEMENT_ID#.php?ID=#SECTION_ID#"    
                            ),
"VARIABLE_ALIASES" => array(
                     "list" => array(),
                     "section" => array(
                                   "IBLOCK_ID" => "ID"),
                     "element" => array(
                                   "SECTION_ID" => "ID",),

Example 2:

Now we want the bitrix:catalog component to handle the following paths:

/fld/cat.php – for catalog index;
/fld/cat.php?BID=catalog_code&SID=group_code – for product groups;
/fld/cat.php?ID=product_code&SID=group_code – for detailed information about a product.

Specify the following assignments in the component input parameters:

"SEF_MODE" => "N",
"VARIABLE_ALIASES" => array(
                           "IBLOCK_ID" => "BID",
                           "SECTION_ID" => "SID",
                           "ELEMENT_ID" => "ID",
                           ),

Using custom template engines

Components can use any template engine that can be plugged in to PHP.

To add a new template engine, edit the /bitrix/php_interface/init.php file as follows:

1. Add a global variable $arCustomTemplateEngines containing an associated arrays, each element of which having the following format:

"template_engine_id" => array( 
"templateExt" => array("ext1"[, "ext2"...]),
"function" => "engine_activator_function"     
)

here:
template_engine_id – an arbitrary unique identifier;
extentionN – the extension of files that will be handled by this template engine;
engine_activator_function – the name of a function that will be called whenever a component template has the specified extension.

2. Declare the engine activator functions:

function engine_activator_function_name($templateFile, $arResult, $arParams, $arLangMessages, $templateFolder, $parentTemplateFolder, $template)

here:
$templateFile – the path to a template file relative to the site root;
$arResult – an array of the component return values;
$arParams – an array of the component input parameters;
$arLangMessages – an array of the template language dependent messages;
$templateFolder – the path to the template folder relative to the site root (empty if a template is not in a folder);
$parentTemplateFolder – the path to a composite component template folder relative to the site root (empty if the component is orphan);
$template – the template instance.

Consider the following examples of adding the template engines.


Adding the Smarty template engine

Declare the Smarty engine in the $arCustomTemplateEngines array:

global $arCustomTemplateEngines; 
     $arCustomTemplateEngines=array( 
     "smarty" => array( 
                       "templateExt" => array("tpl"), 
                       "function" => "SmartyEngine" 
                       ), 
     );

Now, declare the SmartyEngine function and initialize the engine parameters according to the Smarty requirements (see the Smarty help). Then, pass the component return variables, the input parameter variables, the language dependent message variables etc. to Smarty. Finally, the call the Smarty preprocessor/render method:

function SmartyEngine($templateFile, $arResult, $arParams, 
      $arLangMessages, $templateFolder, $parentTemplateFolder, $template) 
{ 
 if (!defined("SMARTY_DIR")) 
     define("SMARTY_DIR", "<absolute path to Smarty>/libs/"); 
 require_once( '<absolute path to Smarty>/libs/Smarty.class.php' ); 
 $smarty = new Smarty; 
 $smarty->compile_dir = "<absolute path to Smarty>/templates_c/"; 
 $smarty->config_dir = "<absolute path to Smarty>/configs/"; 
 $smarty->template_dir = "<absolute path to Smarty>/templates/"; 
 $smarty->cache_dir = "<absolute path to Smarty>/cache/"; 
 $smarty->compile_check = true; 
 $smarty->debugging = false; 
 $smarty->assign("arResult", $arResult); 
 $smarty->>assign("arParams", $arParams); 
 $smarty->assign("MESS", $arLangMessages); 
 $smarty->assign("templateFolder", $templateFolder); 
 $smarty->assign("parentTemplateFolder", $parentTemplateFolder); 
 $smarty->display( $_SERVER["DOCUMENT_ROOT"].$templateFile ); 
}
Replace the <absolute path to Smarty> string with the full path to the Smatry engine.

Adding the XML/XSLT engine

First, initialize the engine:

global $arCustomTemplateEngines; 
$arCustomTemplateEngines = array( 
   "xslt" =< array( 
                  "templateExt" =< array("xsl"), 
                  "function" =< "XSLTEngine" 
                   ), 
);

Declare the engine initializing function:

function CreateXMLFromArray($xDoc, $xNode, $ar) 
{ 
 foreach($ar as $key=<$val) 
   { 
   if(!is_string($key) || strlen($key)<=0) 
      $key = "value"; 
   $xElement = $xDoc->createElement($key); 
   if(is_array($val)) 
     { 
      CreateXMLFromArray($xDoc, $xElement, $val); 
     } 
   else 
     { 
     $xElement->appendChild($xDoc->createTextNode(iconv( SITE_CHARSET, "utf-8", $val))); 
     } 
   $xNode->appendChild($xElement); 
   } 
return $xNode; 
}

Activate the engine:

function XSLTEngine($templateFile, $arResult, $arParams, $arLangMessages, 
           $templateFolder, $parentTemplateFolder, $template)  
{ 
 $arResult["PARAMS"] = array( 
          "templateFolder" => $templateFolder, 
          "parentTemplateFolder" => $parentTemplateFolder, 
          "arParams" => $arParams, 
          "arLangMessages" => $arLangMessages 
 ); 
 $xDoc = new DOMDocument("1.0", SITE_CHARSET); 
 $xRoot = $xDoc->createElement('result'); 
 CreateXMLFromArray($xDoc, $xRoot, $arResult); 
 $xDoc->appendChild($xRoot); 
 $xXsl = new DOMDocument(); 
 $xXsl->load( $_SERVER["DOCUMENT_ROOT"].$templateFile ); 
 $xProc = new XSLTProcessor; 
 $xProc->importStyleSheet($xXsl); 
 echo $xProc->transformToXML($xDoc); 
}

Caching in Components

Dynamic components should use caching to accelerate the processing of client queries and decrease the server load. Generally, only visitor-independent information can be cached. For example, the site index page is usually the same for all visitors. Hence, the news data need not be fetched from database every time. The cache lifetime may vary depending on the frequency of updates. However, sometimes it is reasonable to cache information that pertains to a visitor.

Components 2.0 have built-in cache support. The components that support caching show cache control parameters in the component property sheet:

The following three cache modes exist:

  • Autocache
  • (Always) Cache
  • Don't cache

If the option Cache if the filter is active is active, the data fetched to a visitor as a result of a filtered search request, will be cached. This will use the specified cache mode and lifetime.

Autocache

The autocache mode can be controlled on the Settings -> System settings -> Cache settings page:

You can configure the cache mode for components that support caching irrespective of this setting.

Note! The autocache mode use implies that the information obtained and rendered by components is updated according to the cache preferences of individual components.

You can control caching for components whose cache setting is Auto using just this button in Settings -> System settings -> Cache settings.

(Always) Cache

This mode specifies that the component output is always cached irrespective of the system-wide cache mode as frequently as selected in the component cache settings.

Don't cache

It this option is selected, no caching takes place, irrespective of other cache settings.

Note! If the cache lifetime is set to zero, caching never occurs.

Any of the following actions update cached page objects:

  1. Opening a page and updating it by clicking the cache clear button:

  2. If a component supports caching, the command Clear component's cache is available irrespective of the selected cache mode; this command wipes the cache and forces the page to refresh its dynamic data:

  3. Switching a component to Do not cache mode in the component settings:

Using SEF URL's

This chapter describes the main concepts of URL processing mechanism and how components function in SEF mode.

SEF URL Configuration

As of version 5.1.8 and higher, the system kernel is empowered with the redirection mechanism which is used to support SEF URL (Search Engine Friendly URL).

URL Rewrite

URL Rewrite enables a page to respond not only at a physical address, but also at any other requested URL. For example, you can configure the URL processing settings to make /fld/c.php that respond at:

   /fld/c.php?id=15

respond also at:

   /catalog/15.php

The URL at which a page responds must not exist on a server. If it does, the system will return a page that exists at this URL, and no URL rewrite will take place.

The URL rewrite rules can be are configured in /bitrix/admin/urlrewrite_list.php.

The URL rewrite mechanism has been developed mainly for components 2.0 supporting SEF URL. However, this feature can be used to redefine any other URL.

When adding to a page a SEF URL enabled component, a URL rewrite rule is created automatically (if the file is saved using system API). Otherwise, (for example, when uploading files via FTP), you have to re-create the rules (use the toolbar button on the rule configuration page).

Enabling the URL rewrite mechanism

  1. If the 404 error processing is enabled for Apache, the ErrorDocument option or similar instruction exists in .htaccess:

       ErrorDocument 404 /404.php,

    Edit the file 404.php by typing the following command at the beginning of the file:

       include_once( $_SERVER['DOCUMENT_ROOT']. '/bitrix/modules/main/include/urlrewrite.php' );

  2. If Apache used the mod_rewrite module, specify the following instructions (for example, in the file .htaccess):

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !/bitrix/urlrewrite.php$
    RewriteRule ^(.*)$ /bitrix/urlrewrite.php [L]
    </IfModule>

    Once you have made the described changes, the standard SEF support will be enabled.

Simple test to verify the URL Rewrite settings

  1. Open Settings –> Product settings –> URLs processing:

    Click on image to enlarge

  2. Click New record, select the required site and fill in the form:
    Condition: #^/sef_test/# 
    Component: none
    File: /index.php (or specify a required file)
    Rule: none

    Save changes.

  3. Open a page in the directory /sef_test/.
    For example: http://localhost/sef_test/test.html.

    If SEF URL is in effect, you will see the contents of a page specified in the File field.

Examples

  1. If the following rule exists:

       Condition = #^/gallery/#
       File = /max/images/index.php

    and a visitor requests the page /gallery/38.php that does not exist, the URL rewrite system will return the page /max/images/index.php.

  2. If the following exists:

       Condition = #^/index/([0-9]+)/([0-9]+)/#
       Rule = mode=read&CID=$1&GID=$2
       File = /newforum/index.php

    and a visitor requests /index/5/48/, the system will return /newforum/index.php?mode=read&CID=5&GID=48.

  3. The following rule:

       Condition = #(.+?)\\.html(.*)#
       Rule = $1.php$2

    returns /about/company.php?show in reply to a request for /about/company.html?show.

The internals of composite component operation in SEF mode

The composite components have a built-in SEF URL generator. These components can take the SEF_MODE input parameter that can be Y or N. If SEF_MODE is N, the component works with physical links and passes all parameters via HTTP standard request parameters. For example,

   /fld/cat.php?IBLOCK_ID=12&SECTION_ID=371.

If SEF_MODE is Y, the component generates and processes links using templates. For example, it can process the link

   /catalog/section/371.php?IBLOCK_ID=12,

even if the component is in the /fld/cat.php file.

If SEF_MODE is Y, the component must have the SEF_FOLDER parameter that contains the path to the component working directory. This path can be the same as the physical path or it can be different. For example, the bitrix:catalog component in a file /fld/cat.php can have the parameters SEF_MODE = Y and SEF_FOLDER=/catalog/. The component will respond to requests having /catalog/... in URL. By default, the editor must set the current physical path of a current file.

Composite SEF URL enabled components must be assigned a set of default path templates. For example, the bitrix:catalog component can define the following array:

$arDefaultUrlTemplatesSEF = array( 
      "list" => "index.php", 
      "section" => "section.php?IBLOCK_ID=#IBLOCK_ID#&SECTION_ID=#SECTION_ID#",
      "element" => "element.php?ELEMENT_ID=#ELEMENT_ID#" 
  );

These path templates can be redefined using the input parameter SEF_URL_TEMPLATES containing a new array of all or some path templates.

When saving a page having a component that operates in SEF mode, the editor creates or updates a URL Rewrite system record. For example, when saving the file /fld/cat.php containing the bitrix:catalog SEF mode component whose parameter is SEF_FOLDER=/catalog/, the following record is created or updated:

array( 
 "CONDITION" => "#^/catalog/#", 
 "ID" => "bitrix:catalog", 
 "PATH" => "/fld/cat.php" 
  ),
  • CONDITION contains the value of SEF_FOLDER enclosed in #^ and #;
  • ID is set to the component name;
  • PATH contains the physical path to the file to which the component is added.

If a record with such PATH and ID already exists, it is updated; otherwise, it is created.

At runtime, a request for a non-existing page starts the URL Rewrite mechanism that looks up the rewrite table by CONDITION and passes control over to a page specified in PATH. The component on the PATH page determines the requested page by the path templates and restores the variables on the path.

Note! Each path template must be unique in its static part. You must carefully check the uniqueness in the visual editor. The following examples illustrate this requirement.

The templates:

"section" => "section/#SECTION_ID#.php?IBLOCK_ID=#IBLOCK_ID#", 
"element" => "element/#ELEMENT_ID#.php"

are valid because the static parts section and element are different.

The templates:

"section" => "#SECTION_ID#.php?IBLOCK_ID=#IBLOCK_ID#", 
"element" => "#ELEMENT_ID#.php"

are invalid because there are no static parts that are different.

As you can see, file extensions, parameters and macros are not treated as static parts.