Полезные примеры кода, готовые решения и технические статьи для разработки на Bitrix. Делюсь опытом и наработками.
Создание компонента каталога с AJAX-фильтрацией и пагинацией. Поддержка SEF URL и кеширования.
arResult = [
'ITEMS' => $this->getItems(),
'FILTER' => $this->getFilter(),
'PAGINATION' => $this->getPagination()
];
$this->includeComponentTemplate();
}
private function getItems()
{
$filter = ['ACTIVE' => 'Y'];
// Применяем фильтры
if ($this->arParams['FILTER']) {
$filter = array_merge($filter, $this->arParams['FILTER']);
}
$dbRes = CIBlockElement::GetList(
['SORT' => 'ASC'],
$filter,
false,
['nPageSize' => 20],
['ID', 'NAME', 'DETAIL_URL', 'PREVIEW_PICTURE']
);
$items = [];
while ($item = $dbRes->GetNext()) {
$items[] = $item;
}
return $items;
}
}
Класс для безопасной интеграции с внешними API. Включает обработку ошибок, логирование и кеширование.
baseUrl = rtrim($baseUrl, '/');
$this->token = $token;
}
public function request($method, $endpoint, $data = null)
{
$url = $this->baseUrl . '/' . ltrim($endpoint, '/');
$headers = [
'Authorization: Bearer ' . $this->token,
'Content-Type: application/json',
'Accept: application/json'
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CUSTOMREQUEST => strtoupper($method)
]);
if ($data && in_array($method, ['POST', 'PUT', 'PATCH'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL Error: " . $error);
}
$decodedResponse = json_decode($response, true);
if ($httpCode >= 400) {
$this->logError($httpCode, $response);
throw new Exception("HTTP Error: " . $httpCode);
}
return $decodedResponse;
}
private function logError($code, $response)
{
AddMessage2Log([
'error_code' => $code,
'response' => $response,
'timestamp' => date('Y-m-d H:i:s')
], 'api_errors');
}
}
Методы оптимизации работы с базой данных в Bitrix: пакетная обработка, умное кеширование, оптимизация выборок.
initCache($this->cacheTime, $cacheId, '/iblock_elements/')) {
return $cache->getVars();
}
$cache->startDataCache();
// Используем минимум полей для начальной выборки
$dbRes = CIBlockElement::GetList(
['SORT' => 'ASC'],
array_merge(['IBLOCK_ID' => $iblockId], $filter),
false,
false,
['ID', 'NAME', 'CODE']
);
$elements = [];
$elementIds = [];
while ($element = $dbRes->Fetch()) {
$elements[$element['ID']] = $element;
$elementIds[] = $element['ID'];
}
// Пакетно получаем свойства
if (!empty($elementIds)) {
$this->attachProperties($elements, $elementIds);
}
$cache->endDataCache($elements);
return $elements;
}
private function attachProperties(&$elements, $elementIds)
{
$chunks = array_chunk($elementIds, $this->batchSize);
foreach ($chunks as $chunk) {
$dbProps = CIBlockElement::GetPropertyValues(
false,
['ID' => $chunk]
);
while ($prop = $dbProps->Fetch()) {
if (isset($elements[$prop['IBLOCK_ELEMENT_ID']])) {
$elements[$prop['IBLOCK_ELEMENT_ID']]['PROPERTIES'][$prop['CODE']] = $prop;
}
}
}
}
}
Комплексная система защиты форм и пользовательского ввода от основных типов атак.
$rule) {
$value = $input[$field] ?? null;
if (isset($rule['required']) && $rule['required'] && empty($value)) {
$errors[$field] = 'Поле обязательно для заполнения';
continue;
}
if (!empty($value)) {
if (isset($rule['min_length']) && strlen($value) < $rule['min_length']) {
$errors[$field] = "Минимальная длина: {$rule['min_length']} символов";
}
if (isset($rule['max_length']) && strlen($value) > $rule['max_length']) {
$errors[$field] = "Максимальная длина: {$rule['max_length']} символов";
}
if (isset($rule['pattern']) && !preg_match($rule['pattern'], $value)) {
$errors[$field] = 'Неверный формат данных';
}
}
}
return $errors;
}
}
Универсальный класс для работы с кешированием данных с поддержкой тегированного кеша.
defaultTtl;
if ($cache->initCache($ttl, $key, '/smart_cache/')) {
return $cache->getVars();
}
if (is_callable($callback)) {
$cache->startDataCache();
$data = $callback();
if (!empty($tags)) {
TaggedCache::addTags($cache, $tags);
}
$cache->endDataCache($data);
return $data;
}
return null;
}
public function delete($key)
{
$cache = Cache::createInstance();
$cache->clean($key, '/smart_cache/');
}
public function clearByTag($tag)
{
TaggedCache::clearByTag($tag);
}
}
Готов помочь внедрить любое из этих решений в ваш проект или создать кастомное решение под ваши задачи.
Обсудить проект