Goldensites. Создание сайтов. Разработка сайтов.

Новое на сайте

Редизайн сайта для Avantage, г.Новосибирск
Сайт на домене www.avantage-sib.ru; Разработка эксклюзивного дизайна в соответствии с
Создание сайта для оценочной компании Эстима, г.Барнаул
Сайт на домене www.estimacom.ru; Разработка эксклюзивного дизайна в соответствии с
Разработка сайта для ООО Алтай-Метран-Сервис
Сайт на домене www.ams-bar.ru; Разработка эксклюзивного дизайна для организации, занимающейся
Добавить сайт в каталог лучшихсайтов Joomla!

Вход в личный кабинет Goldensites

LiveZilla Live Help

Портфолио по дизайну сайтов, разработке сайтов, созданию фирменного стиля

Разработка компонента Joomla! 1.6 (часть 6) - Используем базу данных

Компоненты Joomla! 1.6.x обычно управляют своим содержанием, используя базу данных. Во время установки/удаления/обновления компоненты, Вы можете выполнять SQL-запросы, используя для этого файлы, содержащие SQL-код.

Создаем файлы yoursite.ru/administrator/components/com_helloworld/sql/install.mysql.utf8.sql components/com_helloworld/ и yoursite.ru/administrator/components/com_helloworld/sql/updates/mysql/0.0.6.sql содержащие код

DROP TABLE IF EXISTS `jos_helloworld`;
 
CREATE TABLE `jos_helloworld` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `greeting` varchar(25) NOT NULL,
   PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
 
INSERT INTO `jos_helloworld` (`greeting`) VALUES
        ('Hello World!'),
        ('Good bye World!');


Теперь создадим файл удаления компонента Joomla! 1.6.x yoursite.ru/administrator/components/com_helloworld/sql/uninstall.mysql.utf8.sql

DROP TABLE IF EXISTS `jos_helloworld`


Далее делаем изменения в файле helloworld.xml
<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="1.6.0" method="upgrade">

<name>Hello World!</name>
<!-- The following elements are optional and free of formatting conttraints -->
<creationDate>November 2009</creationDate>
<author>John Doe</author>
<authorUrl>http://www.example.org</authorUrl>
<copyright>Copyright Info</copyright>
<license>License Info</license>
<!-- The version string is recorded in the components table -->
<version>0.0.6</version>
<!-- The description is optional and defaults to the name -->
<description>Description of the Hello World component ...</description>

<install> <!-- Runs on install -->
<sql>
<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
</sql>
</install>
<uninstall> <!-- Runs on uninstall -->
<sql>
<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
</sql>
</uninstall>
<update> <!-- Runs on update; New in 1.6 -->
<schemas>
<schemapath type="mysql">sql/updates/mysql</schemapath>
</schemas>
</update>

<!-- Site Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /site/ in the package -->
<files folder="site">
<filename>index.html</filename>
<filename>helloworld.php</filename>
<filename>controller.php</filename>
<folder>views</folder>
<folder>models</folder>
</files>

<administration>
<!-- Administration Menu Section -->
<menu>Hello World!</menu>
<!-- Administration Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /admin/ in the package -->
<files folder="admin">
<!-- Admin Main File Copy Section -->
<filename>index.html</filename>
<filename>helloworld.php</filename>
<!-- SQL files section -->
<folder>sql</folder>
<!-- tables files section -->
<folder>tables</folder>
<!-- models files section -->
<folder>models</folder>
</files>
</administration>

</extension>
До настоящего времени мы использовали громоздкий код для выбора выводимого компонентом сообщения. Теперь мы будем использовать базу данных для вывода сообщения, в файле yoursite.ru/components/com_helloworld/views/helloworld/tmpl/default.xml делаем ряд изменений

<?xml version="1.0" encoding="utf-8"?>
<metadata>
        <layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">
                <message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>
        </layout>
        <fields
                name="request"
                addfieldpath="/administrator/components/com_helloworld/models/fields"
        >
                <fieldset name="request">
                        <field
                                name="id"
                                type="helloworld"
                                label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
                                description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
                        />
                </fieldset>
        </fields>
</metadata>


Мы добавили новый тип поля и указали движку брать значения для этого поля из "/administrator/components/com_helloworld/models/fields".
Создаем файл yoursite.ru/administrator/components/com_helloworld/models/fields/helloworld.php

<?php
// No direct access to this file
defined('_JEXEC') or die;
 
// импортируем тип поля списка
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
 
/**
 * HelloWorld Form Field class for the HelloWorld component
 */
class JFormFieldHelloWorld extends JFormFieldList
{
        /**
         * Тип поля
         *
         * @var         string
         */
        protected $type = 'HelloWorld';
 
        /**
         * Метод для определения опций списка
         *
         * @Возвращает массив опций
         */
        protected function getOptions() 
        {
                $db = JFactory::getDBO();
                $query = $db->getQuery(true);
                $query->select('id,greeting');
                $query->from('jos_helloworld');
                $db->setQuery((string)$query);
                $messages = $db->loadObjectList();
                $options = array();
                if ($messages)
                {
                        foreach($messages as $message) 
                        {
                                $options[] = JHtml::_('select.option', $message->id, $message->greeting);
                        }
                }
                $options = array_merge(parent::getOptions(), $options);
                return $options;
        }
}
?>


Новый тип поля выводит список из сообщений, доступных для вывода компонентом. Вы можете увидеть этот список в менеджере меню компонента helloworld.

Выводим на экран выбранное сообщение
Когда пункт меню нашего компонента создается или обновляется, Joomla! сохраняет идентификатор сообщения. Модель HelloWorldModelHelloWorld теперь должна получить этот идентификатор, определить по ему сообщение в БД и вывести его на экран.
Редактируем yoursite.ru/components/com_helloworld/models/helloworld.php

<?php
// запрет на прямой доступ к файлу
defined('_JEXEC') or die('Restricted access');
 
// импорт библиотек
jimport('joomla.application.component.modelitem');
 
/**
 * HelloWorld Model
 */
class HelloWorldModelHelloWorld extends JModelItem
{
        //определяем переменную для хранения сообщения
        protected $msg;
 
        /**
         * Возвращает ссылку на объект таблицы
         *
         * @param       type    Тип таблицы
         * @param       string  Префикс для табличного имени класса.
         * @param       array   Конфигурационный массив для модели.
         * @return      JTable   Объкт базы данных
         * @since       1.6
         */
        public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array()) 
        {
                return JTable::getInstance($type, $prefix, $config);
        }
        /**
         * Возвращает сообщение
         */
        public function getMsg() 
        {
                if (!isset($this->msg)) 
                {
                        $id = JRequest::getInt('id');
                        $table = $this->getTable();
 
                        //получаем сообщение
                        $table->load($id);
 
                        // присваиваем
                        $this->msg = $table->greeting;
                }
                return $this->msg;
       }
}


Теперь осталось только определить табличный класс TableHelloWorld
Создаем файл yoursite.ru/components/com_helloworld/tables/helloworld.php

<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
 
// import Joomla table library
jimport('joomla.database.table');
 
/**
 * Hello Table class
 */
class HelloWorldTableHelloWorld extends JTable
{
        /**
         * Constructor
         *
         * @param object Database connector object
         */
        function __construct(&$db) 
        {
                parent::__construct('jos_helloworld', 'id', $db);
        }



Установочный пакет

* helloworld.xml
* site/index.html
* site/helloworld.php
* site/controller.php
* site/views/index.html
* site/views/helloworld/index.html
* site/views/helloworld/view.html.php
* site/views/helloworld/tmpl/index.html
* site/views/helloworld/tmpl/default.xml
* site/views/helloworld/tmpl/default.php
* site/models/index.html
* site/models/helloworld.php
* admin/index.html
* admin/helloworld.php
* admin/sql/index.html
* admin/sql/install.mysql.utf8.sql
* admin/sql/uninstall.mysql.utf8.sql
* admin/sql/updates/index.html
* admin/sql/updates/mysql/index.html
* admin/sql/updates/mysql/0.0.1.sql
* admin/sql/updates/mysql/0.0.6.sql
* admin/models/index.html
* admin/models/fields/index.html
* admin/models/fields/helloworld.php
* admin/tables/index.html
* admin/tables/helloworld.php

Создайте установочний файл ZIP или загрузите пакет Установите его с помощью менеджера расширений Joomla!1.6. Добавьте пункт меню для этого компонента в менеджере меню.

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="1.6.0" method="upgrade">

<name>Hello World!</name>
<!-- The following elements are optional and free of formatting conttraints -->
<creationDate>November 2009</creationDate>
<author>John Doe</author>
<authorEmail> Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра. </authorEmail>
<authorUrl>http://www.example.org</authorUrl>
<copyright>Copyright Info</copyright>
<license>License Info</license>
<!-- The version string is recorded in the components table -->
<version>0.0.6</version>
<!-- The description is optional and defaults to the name -->
<description>Description of the Hello World component ...</description>

<install> <!-- Runs on install -->
<sql>
<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
</sql>
</install>
<uninstall> <!-- Runs on uninstall -->
<sql>
<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
</sql>
</uninstall>
<update> <!-- Runs on update; New in 1.6 -->
<schemas>
<schemapath type="mysql">sql/updates/mysql</schemapath>
</schemas>
</update>

<!-- Site Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /site/ in the package -->

<files folder="site">
<filename>index.html</filename>
<filename>helloworld.php</filename>
<filename>controller.php</filename>
<folder>views</folder>
<folder>models</folder>
</files>

<administration>
<!-- Administration Menu Section -->
<menu>Hello World!</menu>
<!-- Administration Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /admin/ in the package -->

<files folder="admin">
<!-- Admin Main File Copy Section -->
<filename>index.html</filename>
<filename>helloworld.php</filename>
<!-- SQL files section -->
<folder>sql</folder>
<!-- tables files section -->
<folder>tables</folder>
<!-- models files section -->
<folder>models</folder>
</files>
</administration>

</extension>

Комментарии 

 
#3 ThePlace 07.09.2011 13:42
переводчик не виноват)
а вообще, автора надо указывать
Цитировать
 
 
#2 kira 20.07.2011 17:29
С этого шага вообще непонятно написано. Автор, плохо! мало комментариев и скудные разъяснения :-?
Цитировать
 
 
#1 Вася 30.05.2011 15:18
При установке компонента ошибка: Ошибка при создании меню панели управления.
Цитировать
 

Есть что почитать

Создание сайта для "Лимо-Карс Барнаул"
Регистрация доменного имени limocars22.ru; Разработка эксклюзивного дизайна в соответствии с
Не работает Jquery на сайте Joomla - нужно отключить mootools!
Порой, чтобы ваши скрипты или библиотеки не конфликтовали (например, jQuery
Создание сайта-каталога
Вам нужно удобное и эффективное средство для информирования покупателей, клиентов
Как поместить (вывести) модуль в статью Joomla! 1.6.x
Модули в Joomla! 1.6.x имеют позиции для вывода, которые определяются
Разный вывод категорий Joomla или делаем свой шаблон для вывода категории Joomla
Часто возникают ситуации, когда нужно разные категории в Joomla! выводить