Ниже представлена небольшая шпаргалка с основными классами, а также методами, наиболее часто используемыми при разработке:
Документ
- $doc = JFactory::getDocument()
- Объект документа
- $doc->getTitle()
- Получить заголовок страницы
- $doc->setTitle()
- Задать заголовок страницы
- $doc->getDescription()
- Получить значение meta Description
- $doc->setDescription()
- Задать значение meta Description
- $doc->getMetaData('keywords')
- Получить keywords
- $doc->setMetaData('keywords')
- Задать keywords
- JHtml::_('script', 'jquery.min.js')
- Подключить javascript в блок head
- JHtml::_('stylesheet', 'user.css');
- Подключить css в блок head
База данных
Выборка \ SELECT
$db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering'))); $query->from($db->quoteName('#__user_profiles')); $query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'custom.%\'')); $query->order('ordering ASC'); $db->setQuery($query); $results = $db->loadObjectList();
Джоины \ JOIN
$db = JFactory::getDbo(); $query = $db->getQuery(true); $query ->select(array('a.*', 'b.username', 'b.name')) ->from($db->quoteName('#__content', 'a')) ->join('INNER', $db->quoteName('#__users', 'b') . ' ON (' . $db->quoteName('a.created_by') . ' = ' . $db->quoteName('b.id') . ')') ->where($db->quoteName('b.username') . ' LIKE \'a%\'') ->order($db->quoteName('a.created') . ' DESC');
Вставка \ INSERT
$db = JFactory::getDbo(); $query = $db->getQuery(true); $columns = array('user_id', 'profile_key', 'profile_value', 'ordering'); $values = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1); $query ->insert($db->quoteName('#__user_profiles')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->execute();
Обновление \ UPDATE
$db = JFactory::getDbo(); $query = $db->getQuery(true); $fields = array( $db->quoteName('profile_value') . ' = ' . $db->quote('Updating custom message for user 1001.'), $db->quoteName('ordering') . ' = 2' ); $conditions = array( $db->quoteName('user_id') . ' = 42', $db->quoteName('profile_key') . ' = ' . $db->quote('custom.message') ); $query->update($db->quoteName('#__user_profiles'))->set($fields)->where($conditions); $db->setQuery($query); $result = $db->execute();
Удаление \ DELETE
$db = JFactory::getDbo(); $query = $db->getQuery(true); $conditions = array( $db->quoteName('user_id') . ' = 1001', $db->quoteName('profile_key') . ' = ' . $db->quote('custom.%') ); $query->delete($db->quoteName('#__user_profiles')); $query->where($conditions); $db->setQuery($query); $result = $db->execute();
Получить подкатегории:
$jcats = JCategories::getInstance('Content'); //объект для работы с категориями $cat = $jcats->get(8); //catalog category == 8 foreach ($cat->getChildren() as $id => $child) { $sections[$id]['title'] = $child->title; $sections[$id]['id'] = $child->id; //.......... if ( $child->getChildren() ){ foreach ( $child->getChildren() as $cid => $deeperChild ){ $sections[$id]['subcats'][$cid]['id'] = $deeperChild->id; $sections[$id]['subcats'][$cid]['title'] = $deeperChild->title; } } else{ //........... } }
Получить список материалов указанной категории с полями custom_fields:
public static function getItems(){ $modelC = JModelLegacy::getInstance('Category', 'ContentModel', array( 'ignore_request' => true )); //здесь параметр 'ignore_request' => true означает, что модель "игнорирует запрос", то есть она не выцепляет самостоятельно состояние для модели из query string (catid, articleId, start итд) //поэтому мы задаем ручками как бы "фильтры" (caregoryId, published=1) - устанавливаем состояние модели через метод setState(), чтобы затем вызвать метод getItems() //полный список возможных фильтров вы можете увидеть в модели, в методе getListQuery, там она поэтапно собирает все возможные фильтры для выборки из бд благодаря методу getState() $modelC->setState('category.id', 10); //для catId == 10 $modelC->setState('filter.published', 1); $app = JFactory::getApplication('site'); $itemid = $app->input->get('id', 0, 'int') . ':' . $app->input->get('Itemid', 0, 'int'); $app->setUserState( 'com_content.category.list.' . $itemid . '.filter_order', 'ordering'); $app->setUserState( 'com_content.category.list.' . $itemid . '.filter_order_Dir', 'ASC'); $itms = $modelC->getItems(); $modelF = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true)); $categoryFieldsIds = array(3,5); //для field_id == 3,5 foreach ( $itms as $itm ){ $itm->cfields = $modelF->getFieldValues($categoryFieldsIds, $itm->id); } return $itms; }
Вывод модулей в компоненте \ переопределении \ странице ошибок error.php
jimport( 'joomla.application.module.helper' ); $module = JModuleHelper::getModules('our-module'); $attribs['style'] = 'xhtml'; echo JModuleHelper::renderModule($module[0], $attribs);
Вывод плагина из группы content в шаблоне или переопределении:
$text = JHtml::_('content.prepare', $text); //для события onContentPrepare в классе модуля. в $text передаем искомую регулярку {pluginname} она же выдаст результат работы плагинаили:
$article = new stdClass; $article->text = $text; $params = new JObject; JPluginHelper::importPlugin('content'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onContentPrepare', array('some.context', &$article, &$params, 0));
Кастомный Layout из конкретного файла
$layout = new JLayoutFile('joomla.content.tags', JPATH_SITE . '/components/com_mycomponent/layouts'); $layout->render($itemTags);
Сессии
$session = JFactory::getSession(); $session->set( 'myVar', 500 ); // установка значения $session->get('myVar', 'значение по умолчанию'); //получение значения $session->getName(); //имя сессии $session->getId(); //id сессии
Почта \ JMail
$mailer = JFactory::getMailer(); $mailer->IsHTML( true ); $mailer->setSender( array( 'email_отправителя', 'имя отправителя' ) ); $mailer->addRecipient( 'email_получателя' ); $mailer->addCC( 'email_получателя_копии' ); $mailer->setBody('<h1>Hello User!</h1>'); $mailer->send();
Генерация ЧПУ \ SEF
$link = JRoute::_(ContentHelperRoute::getArticleRoute($this->item->slug, $this->item->catid)); //здесь необходимо позаботиться, чтобы был подключен хелпер ContentHelperRoute // параметры: $this->item->slug - строка вида id_материала + ':' + alias материала //$this->item->catid категория материала