Фишки Opencart
События event
Создание события
$this->event->trigger(‘post.admin.tag.add’, $tag_id);
Упрощалки
Для выполнения сразу множества запросов средствами opencart
protected function multiquery( $sql ) { foreach (explode(";n", $sql) as $sql) { $sql = trim($sql); if ($sql) { $this->db->query($sql); } } } $sql = "DELETE FROM `".DB_PREFIX."product` WHERE `product_id` = '$product_id';n"; $this->multiquery( $sql );
Проверки и другие хелперы
встретил в Opencart 3.0.2rus
filter_var($this->request->post['seller_email'], FILTER_VALIDATE_email)
Проверка метода поста
if (isset($this->request->get['category_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
Множественные замены
// Payment Address if ($order_info['payment_address_format']) { $format = $order_info['payment_address_format']; } else { $format = '{firstname} {lastname}' . "n" . '{company}' . "n" . '{address_1}' . "n" . '{address_2}' . "n" . '{city} {postcode}' . "n" . '{zone}' . "n" . '{country}'; } $find = array( '{firstname}', '{lastname}', '{company}', '{address_1}', '{address_2}', '{city}', '{postcode}', '{zone}', '{zone_code}', '{country}' ); $replace = array( 'firstname' => $order_info['payment_firstname'], 'lastname' => $order_info['payment_lastname'], 'company' => $order_info['payment_company'], 'address_1' => $order_info['payment_address_1'], 'address_2' => $order_info['payment_address_2'], 'city' => $order_info['payment_city'], 'postcode' => $order_info['payment_postcode'], 'zone' => $order_info['payment_zone'], 'zone_code' => $order_info['payment_zone_code'], 'country' => $order_info['payment_country'] ); $data['payment_address'] = str_replace(array("rn", "r", "n"), '<br />', preg_replace(array("/ss+/", "/rr+/", "/nn+/"), '<br />', trim(str_replace($find, $replace, $format))));
как проверить включен ли https
if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
Получить скрипты и стили
$data[‘links’] = $this->document->getLinks();
$data[‘styles’] = $this->document->getStyles();
$data[‘scripts’] = $this->document->getScripts();
Сгенерировать ссылку, если есть ЧПУ В БД, то должен сработать rewrite, иначе получится длинная ссылка ввида index.php?route=
$this->url->link(‘common/dashboard’, », true);
$lnk = $url->link('product/product', 'path=' . $category_id . '&product_id=' . $row['product_id']); //получится <br><a rel="noreferrer noopener" href="http://magazin.ru/index.php?route=product/product&path=1&product_id=2" target="_blank">http://magazin.ru/index.php?route=product/product&path=1&product_id=2</a>
Подключение главного меню в шапке
<?php if ($this->config->get('gen_topmenu') == '2') { include $wayPath ."/common/menudefault.php"; }
<?php include(DIR_TEMPLATE . '/luxury/template/product/options.tpl'); ?>
Работа с кешем
$cacheKey = md5(serialize(array(__CLASS__, $setting, $this->currency->getId()))); $view = $this->cache->get($cacheKey); $this->cache->set($cacheKey, $view);
HTTP заголовки
$this->response->addHeader('Content-Type: application/json; charset=utf-8'); $this->response->setOutput(json_encode($json));
Отменить кеширование
header(‘Cache-Control: no-cache, no-store’);
JAVASCRIPT
<script type="text/javascript"> loadScript("AWCore/mod/AW_Admin_Order_(add,view,edit)/AW_Admin_Order_(add,view,edit).js", function(){ loadStyle("AWCore/mod/AW_Admin_Order_(add,view,edit)/AW_Admin_Order_(add,view,edit).css"); }); </script>
Как подключить серию контроллеров в контроллере
$data['analytics'] = array(); $analytics = $this->model_extension_extension->getExtensions('analytics'); foreach ($analytics as $analytic) { if ($this->config->get($analytic['code'] . '_status')) { $data['analytics'][] = $this->load->controller('analytics/' . $analytic['code']); } }

class ControllerAnalyticsGoogleAnalytics extends Controller { public function index() { return html_entity_decode($this->config->get('google_analytics_code'), ENT_QUOTES, 'UTF-8'); } }
Остальные манипуляции с контроллерами
Передача инфы в свой контроллер
$template = $this->document->getTemplateFile('information/contact_content.tpl'); $data['content'] = $this->load->view($template, $data); $this->response->setOutput($this->load->controller('common/html', $data));
Конфиги
Работа с путями
Можно вот так задавать пути, чтобы обратиться в соседнюю с catalog папку
$dir_path = DIR_CATALOG.'../landing_pages/'.$landing_name;
Универсальный
чтобы упростить переносы сайта на разные хосты
<?php $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; // HTTP define('HTTP_SERVER', 'http://'.$host.'/'); define('HTTP_IMAGE', 'http://'.$host.'/image/'); define('HTTP_DESIGN', ''); // HTTPS define('HTTPS_SERVER', 'http://'.$host.'/'); define('HTTPS_IMAGE', 'http://'.$host.'/image/'); define('HTTPS_DESIGN', ''); $dir = dirname(__FILE__); // DIR define('DIR_APPLICATION', $dir.'/catalog/'); define('DIR_SYSTEM', $dir.'/system/'); define('DIR_LANGUAGE', $dir.'/catalog/language/'); define('DIR_TEMPLATE', $dir.'/catalog/view/theme/'); define('DIR_CONFIG', $dir.'/system/config/'); define('DIR_IMAGE', $dir.'/image/'); define('DIR_CACHE', $dir.'/system/cache/'); define('DIR_DOWNLOAD', $dir.'/download/'); define('DIR_UPLOAD', $dir.'/system/upload/'); define('DIR_MODIFICATION', $dir.'/system/modification/'); define('DIR_LOGS', $dir.'/system/logs/'); define('DIR_CATALOG', $dir.'/catalog/'); // DB define('DB_DRIVER', 'mysqli'); define('DB_HOSTNAME', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'opencart_flow'); define('DB_PREFIX', 'oc_'); define('ENVIRONMENT', 'LIVE');
Как получить настройки
модуля,если не доступна переменная settings в index(settings). Скорее всего в контроллерах каталога это переменная формируется автоматом
$language_id = $this->config->get('config_language_id'); $setting = $this->model_extension_module->getModule( $this->request->get['module_id']);
Отличие $setting[‘store_id’] от $this->config->get(‘config_store_id’) — первое: из таблицы настроек модулей,второе: из таблицы settings
Как изменить настройки модуля и добавить событие
$this->load->language('catalog/sitemap_manager'); $this->load->model('extension/event'); $this->load->model('setting/setting'); $sitemapManagerSettings = $this->model_setting_setting->getSetting('sitemap_manager'); if (!$sitemapManagerSettings['sitemap_manager_event_status']) { $this->model_extension_event->addEvent( 'sitemap', 'recreateMarketOffers', 'catalog/sitemap_manager/addTaskToGenerateSitemap', 'Генерация карты сайта', 1 ); $sitemapManagerSettings['sitemap_manager_event_status'] = 1; $this->model_setting_setting->editSetting('sitemap_manager', $sitemapManagerSettings); }
Конфиг обычный
<?php ini_set('display_errors', 1); ini_set('log_errors', 1); error_reporting(E_ALL); $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : basename(dirname(__FILE__)); // HTTP define('HTTP_SERVER', 'http://'.$host.'/'); define('HTTP_IMAGE', 'http://'.$host.'/image/'); define('HTTP_DESIGN', ''); // HTTPS define('HTTPS_SERVER', 'https://'.$host.'/'); define('HTTPS_IMAGE', 'https://'.$host.'/image/'); define('HTTPS_DESIGN', ''); $dir = dirname(__FILE__); // DIR define('DIR_APPLICATION', $dir.'/catalog/'); define('DIR_LANGUAGE', DIR_APPLICATION.'language/'); define('DIR_TEMPLATE', DIR_APPLICATION.'view/theme/'); define('DIR_CATALOG', DIR_APPLICATION); define('DIR_LANDING', $dir.'/landing_pages/'); define('DIR_IMAGE', $dir.'/image/'); define('DIR_SYSTEM', $dir.'/system/'); define('DIR_CONFIG', DIR_SYSTEM.'config/'); define('DIR_STORAGE', DIR_SYSTEM.'storage/'); define('DIR_CACHE', DIR_STORAGE.'cache/'); define('DIR_DOWNLOAD', DIR_STORAGE.'download/'); define('DIR_LOGS', DIR_STORAGE.'logs/'); define('DIR_MODIFICATION', DIR_STORAGE.'modification/'); define('DIR_UPLOAD', DIR_STORAGE.'upload/'); // DB define('DB_DRIVER', 'mysqli'); define('DB_HOSTNAME', 'localhost'); define('DB_USERNAME', 'iqcode'); define('DB_PASSWORD', '4Q0l8U3y'); define('DB_DATABASE', 'tsuperbd'); define('DB_PREFIX', 'oc_');
Отладка -debug- движка
global $registry; $registry = $this->registry; set_error_handler('error_handler_for_export_import',E_ALL); register_shutdown_function('fatal_error_shutdown_handler_for_export_import'); try{ } } catch (Exception $e) { $errstr = $e->getMessage(); $errline = $e->getLine(); $errfile = $e->getFile(); $errno = $e->getCode(); $this->session->data['export_import_error'] = array( 'errstr'=>$errstr, 'errno'=>$errno, 'errfile'=>$errfile, 'errline'=>$errline ); if ($this->config->get('config_error_log')) { $this->log->write('PHP ' . get_class($e) . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline); } return; }
Подключение библиотек
$cwd = getcwd(); $dir = (strcmp(VERSION,'3.0.0.0')>=0) ? 'library/export_import' : 'PHPExcel'; chdir( DIR_SYSTEM.$dir ); require_once( 'Classes/PHPExcel.php' ); PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_ExportImportValueBinder() ); chdir( $cwd );
Модели
Как подключить модель из модели
public function __construct($registry) { $this->_config = $registry->get('config'); $this->_cache = $registry->get('cache'); $this->_db = $registry->get('db'); $this->_url = $registry->get('url'); // $this->modelCategory = $this->load->model('catalog/category'); $this->modelCategory = $registry->get('model_catalog_category'); if (isset($registry->get('request')->get['path'])) { $this->_path = explode('_', $registry->get('request')->get['path']); $this->_active = end($this->_path); } }
использование конструктора и подгрузка всяких переменных
public function __construct($registry) { $this->_config = $registry->get('config'); $this->_cache = $registry->get('cache'); $this->_db = $registry->get('db'); $this->_url = $registry->get('url'); $this->modelCategory = $this->load->model('catalog/category'); // $this->modelCategory = $registry->get('model_catalog_category'); if (isset($registry->get('request')->get['path'])) { $this->_path = explode('_', $registry->get('request')->get['path']); $this->_active = end($this->_path); } }
Переменные движка
Как получить переменную registry внутри модели или контроллера
public function __construct( $registry ) { parent::__construct( $registry ); }
Чтобы сделать registry доступной вне класса, например, для функции обработчика ошибок. Нужно прописать вне класса
static $registry = null; function error_handler_for_seller($errno, $errstr, $errfile, $errline) { global $registry; switch ($errno) { case E_NOTICE: case E_USER_NOTICE: $errors = "Notice"; break; case E_WARNING: case E_USER_WARNING: $errors = "Warning"; break; case E_ERROR: case E_USER_ERROR: $errors = "Fatal Error"; break; default: $errors = "Unknown"; break; } $config = $registry->get('config'); $url = $registry->get('url'); $request = $registry->get('request'); $session = $registry->get('session'); $log = $registry->get('log'); if ($config->get('config_error_log')) { $log->write('PHP ' . $errors . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline); } if (($errors=='Warning') || ($errors=='Unknown')) { return true; } $dir = version_compare(VERSION,'3.0','>=') ? 'extension' : 'tool'; if (($errors != "Fatal Error") && isset($request->get['route']) && ($request->get['route']!="$dir/export_import/download")) { if ($config->get('config_error_display')) { echo '<b>' . $errors . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>'; } } else { $session->data['export_import_error'] = array( 'errstr'=>$errstr, 'errno'=>$errno, 'errfile'=>$errfile, 'errline'=>$errline ); $token = version_compare(VERSION,'3.0','>=') ? $request->get['user_token'] : $request->get['token']; $link = $url->link( "$dir/export_import", version_compare(VERSION,'3.0','>=') ? 'user_token='.$token : 'token='.$token, true ); header('Status: ' . 302); header('Location: ' . str_replace(array('&', "n", "r"), array('&', '', ''), $link)); exit(); } return true; }
и внутри класса
global $registry; $registry = $this->registry;
После это можно обращаться к registory OpenCart как к своей родной
$config = $registry->get('config'); $url = $registry->get('url'); $request = $registry->get('request'); $session = $registry->get('session'); $log = $registry->get('log');
Совместимость разных версий
private $dir; private $modules_page; public function __construct($registry) { parent::__construct( $registry ); $this->dir = version_compare(VERSION,'2.3','>=') ? 'extension/module' : 'module'; $this->token = version_compare(VERSION,'3.0','>=') ? 'user_' : ''; $this->modules_page = version_compare(VERSION,'2.1','<=') ? 'extension/module' : version_compare(VERSION,'2.3','<=') ? 'extension/extension' : 'marketplace/extension'; }
$this->response->setOutput($this->load->view( ((version_compare(VERSION, '2.2.0.0') >= 0) ? 'tool/export_import' : 'tool/export_import.tpl'), $data));
$link = $url->link( "$dir/export_import", version_compare(VERSION,'3.0','>=') ? 'user_token='.$token : 'token='.$token, true );
$token = version_compare(VERSION,'3.0','>=') ? $request->get['user_token'] : $request->get['token'];
$dir = version_compare(VERSION,'3.0','>=') ? 'extension' : 'tool';
if (version_compare(VERSION,'3.0','>=')) { class ModelExtensionExportImport extends ModelToolExportImport { } }
Если запрос исходит от пользователя IE, то
if (isset($_SERVER['HTTP_USER_AGENT'])) { // if IE<=8 module do not work if (preg_match('/(?i)msie [1-8]/', $_SERVER['HTTP_USER_AGENT'])) { return FALSE; } }
Валидаторы
if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate())) {}
public function validate(){ if ((utf8_strlen(trim($this->request->post['seller_name'])) < 1) || (utf8_strlen(trim($this->request->post['seller_name'])) > 32)) { $this->error['seller_name'] = $this->language->get('error_seller_name'); } if ((utf8_strlen(trim($this->request->post['seller_address'])) < 1) || (utf8_strlen(trim($this->request->post['seller_address'])) > 32)) { $this->error['seller_address'] = $this->language->get('error_seller_address'); } if ((utf8_strlen(trim($this->request->post['seller_desc'])) < 1) || (utf8_strlen(trim($this->request->post['seller_desc'])) > 32)) { $this->error['seller_desc'] = $this->language->get('seller_desc'); } if ((utf8_strlen($this->request->post['seller_email']) > 96) || !filter_var($this->request->post['seller_email'], FILTER_VALIDATE_email)) { $this->error['seller_email'] = $this->language->get('error_seller_email'); } if ((utf8_strlen($this->request->post['seller_phone']) < 3) || (utf8_strlen($this->request->post['seller_phone']) > 32)) { $this->error['seller_phone'] = $this->language->get('error_seller_phone'); } return !this->error; }
$this->response->redirect($this->url->link('account/seller','', $this->ssl)); $this->session->data['success'] = $this->language->get('text_success');
Работа с формами
if (isset($this->request->post['seller_phone'])) { $data['seller_phone'] = $this->request->post['seller_phone']; } elseif (!empty($customer_info)) { $data['seller_phone'] = $customer_info['seller_phone']; } else { $data['seller_phone'] = ''; }
Авторизация
if (!$this->customer->isLogged()) { $this->session->data['redirect'] = $this->url->link('account/edit', '', true); $this->response->redirect($this->url->link('account/login', '', true)); }
Шапка сайта
динам.подключение стилей и скриптов из контроллера
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment/moment.min.js'); $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment/moment-with-locales.min.js'); $this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js'); $this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
Работа с файлами
чтобы опредедить местоположение скрипта на диске надо залесть в переменную
_SERVER["SCRIPT_FILENAME"]
Работа с сылками
Чтобы подготовить строчку для использования в качестве части url (превратить все не цифро-буквенные символы в %)
$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
чтобы узнать домен вместе с протоколом след.код