Как начать свой компонент на основе Joomla Component Creator

Тема в разделе "Программирование", создана пользователем FeaMor, 10.09.2013.

  1. FeaMor
    Offline

    FeaMor Пользователь

    Регистрация:
    01.09.2008
    Сообщения:
    104
    Симпатии:
    2
    Пол:
    Мужской
    Добрый день!

    Мне нужно написать свой компонент, но т.к. я не сильно шарю во всей системе MVC, решил воспользоваться генерацией начального каркаса компонента через Joomla Component Creator. Я раньше так делал уже и было все просто, в моделях определял переменные, а в видах уже выводил эти переменные как надо. Но сейчас совсем не так просто генерируется компонент, слишком, ну очень слишком много информации начальной....

    Вот какие файлы я имею:
    \controllers\office.php
    \controllers\officeform.php
    \controllers\offices.php
    \models\office.php
    \models\officeform.php
    \models\offices.php
    \views\office\
    \views\officeform\
    \views\offices\
    хотя мне нужен был только одна модель "office", остальные сами создаются, на разных генераторах пробовал...
    Пояните чуточку, зачем остальные файлы нужны и где в них что прописывать свое можно?

    Помогите мне с простым примером, плиз. Например, чтения из базы какой-нить данной и вывод ее в шаблон вида..

    \controllers\office.php

    Код (PHP):
    1. <?php
    2. // No direct access
    3. defined('_JEXEC') or die;
    4.  
    5. require_once JPATH_COMPONENT.'/controller.php';
    6.  
    7. /**
    8.  * Office controller class.
    9.  */
    10. class BsControllerOffice extends BsController
    11. {
    12.  
    13.     /**
    14.      * Method to check out an item for editing and redirect to the edit form.
    15.      *
    16.      * @since   1.6
    17.      */
    18.     public function edit()
    19.     {
    20.         $app            = JFactory::getApplication();
    21.  
    22.         // Get the previous edit id (if any) and the current edit id.
    23.         $previousId = (int) $app->getUserState('com_bs.edit.office.id');
    24.         $editId = JFactory::getApplication()->input->getInt('id', null, 'array');
    25.  
    26.         // Set the user id for the user to edit in the session.
    27.         $app->setUserState('com_bs.edit.office.id', $editId);
    28.  
    29.         // Get the model.
    30.         $model = $this->getModel('Office', 'BsModel');
    31.  
    32.         // Check out the item
    33.         if ($editId) {
    34.             $model->checkout($editId);
    35.         }
    36.  
    37.         // Check in the previous user.
    38.         if ($previousId) {
    39.             $model->checkin($previousId);
    40.         }
    41.  
    42.         // Redirect to the edit screen.
    43.         $this->setRedirect(JRoute::_('index.php?option=com_bs&view=officeform&layout=edit', false));
    44.     }
    45.  
    46.     /**
    47.      * Method to save a user's profile data.
    48.      *
    49.      * @return  void
    50.      * @since   1.6
    51.      */
    52.     public function save()
    53.     {
    54.         // Check for request forgeries.
    55.         JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
    56.  
    57.         // Initialise variables.
    58.         $app    = JFactory::getApplication();
    59.         $model = $this->getModel('Office', 'BsModel');
    60.  
    61.         // Get the user data.
    62.         $data = JFactory::getApplication()->input->get('jform', array(), 'array');
    63.  
    64.         // Validate the posted data.
    65.         $form = $model->getForm();
    66.         if (!$form) {
    67.             JError::raiseError(500, $model->getError());
    68.             return false;
    69.         }
    70.  
    71.         // Validate the posted data.
    72.         $data = $model->validate($form, $data);
    73.  
    74.         // Check for errors.
    75.         if ($data === false) {
    76.             // Get the validation messages.
    77.             $errors = $model->getErrors();
    78.  
    79.             // Push up to three validation messages out to the user.
    80.             for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
    81.                 if ($errors[$i] instanceof Exception) {
    82.                     $app->enqueueMessage($errors[$i]->getMessage(), 'warning');
    83.                 } else {
    84.                     $app->enqueueMessage($errors[$i], 'warning');
    85.                 }
    86.             }
    87.  
    88.             // Save the data in the session.
    89.             $app->setUserState('com_bs.edit.office.data', JRequest::getVar('jform'),array());
    90.  
    91.             // Redirect back to the edit screen.
    92.             $id = (int) $app->getUserState('com_bs.edit.office.id');
    93.             $this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
    94.             return false;
    95.         }
    96.  
    97.         // Attempt to save the data.
    98.         $return = $model->save($data);
    99.  
    100.         // Check for errors.
    101.         if ($return === false) {
    102.             // Save the data in the session.
    103.             $app->setUserState('com_bs.edit.office.data', $data);
    104.  
    105.             // Redirect back to the edit screen.
    106.             $id = (int)$app->getUserState('com_bs.edit.office.id');
    107.             $this->setMessage(JText::sprintf('Save failed', $model->getError()), 'warning');
    108.             $this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
    109.             return false;
    110.         }
    111.  
    112.            
    113.         // Check in the profile.
    114.         if ($return) {
    115.             $model->checkin($return);
    116.         }
    117.        
    118.         // Clear the profile id from the session.
    119.         $app->setUserState('com_bs.edit.office.id', null);
    120.  
    121.         // Redirect to the list screen.
    122.         $this->setMessage(JText::_('COM_BS_ITEM_SAVED_SUCCESSFULLY'));
    123.         $menu = & JSite::getMenu();
    124.         $item = $menu->getActive();
    125.         $this->setRedirect(JRoute::_($item->link, false));
    126.  
    127.         // Flush the data from the session.
    128.         $app->setUserState('com_bs.edit.office.data', null);
    129.     }
    130.    
    131.    
    132.     function cancel() {
    133.         $menu = & JSite::getMenu();
    134.         $item = $menu->getActive();
    135.         $this->setRedirect(JRoute::_($item->link, false));
    136.     }
    137.    
    138.     public function remove()
    139.     {
    140.         // Check for request forgeries.
    141.         JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
    142.  
    143.         // Initialise variables.
    144.         $app    = JFactory::getApplication();
    145.         $model = $this->getModel('Office', 'BsModel');
    146.  
    147.         // Get the user data.
    148.         $data = JFactory::getApplication()->input->get('jform', array(), 'array');
    149.  
    150.         // Validate the posted data.
    151.         $form = $model->getForm();
    152.         if (!$form) {
    153.             JError::raiseError(500, $model->getError());
    154.             return false;
    155.         }
    156.  
    157.         // Validate the posted data.
    158.         $data = $model->validate($form, $data);
    159.  
    160.         // Check for errors.
    161.         if ($data === false) {
    162.             // Get the validation messages.
    163.             $errors = $model->getErrors();
    164.  
    165.             // Push up to three validation messages out to the user.
    166.             for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
    167.                 if ($errors[$i] instanceof Exception) {
    168.                     $app->enqueueMessage($errors[$i]->getMessage(), 'warning');
    169.                 } else {
    170.                     $app->enqueueMessage($errors[$i], 'warning');
    171.                 }
    172.             }
    173.  
    174.             // Save the data in the session.
    175.             $app->setUserState('com_bs.edit.office.data', $data);
    176.  
    177.             // Redirect back to the edit screen.
    178.             $id = (int) $app->getUserState('com_bs.edit.office.id');
    179.             $this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
    180.             return false;
    181.         }
    182.  
    183.         // Attempt to save the data.
    184.         $return = $model->delete($data);
    185.  
    186.         // Check for errors.
    187.         if ($return === false) {
    188.             // Save the data in the session.
    189.             $app->setUserState('com_bs.edit.office.data', $data);
    190.  
    191.             // Redirect back to the edit screen.
    192.             $id = (int)$app->getUserState('com_bs.edit.office.id');
    193.             $this->setMessage(JText::sprintf('Delete failed', $model->getError()), 'warning');
    194.             $this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
    195.             return false;
    196.         }
    197.  
    198.            
    199.         // Check in the profile.
    200.         if ($return) {
    201.             $model->checkin($return);
    202.         }
    203.        
    204.         // Clear the profile id from the session.
    205.         $app->setUserState('com_bs.edit.office.id', null);
    206.  
    207.         // Redirect to the list screen.
    208.         $this->setMessage(JText::_('COM_BS_ITEM_DELETED_SUCCESSFULLY'));
    209.         $menu = & JSite::getMenu();
    210.         $item = $menu->getActive();
    211.         $this->setRedirect(JRoute::_($item->link, false));
    212.  
    213.         // Flush the data from the session.
    214.         $app->setUserState('com_bs.edit.office.data', null);
    215.     }
    216.    
    217.    
    218. }


    \models\office.php
    Код (PHP):
    1. <?php
    2. // No direct access.
    3. defined('_JEXEC') or die;
    4.  
    5. jimport('joomla.application.component.modelform');
    6. jimport('joomla.event.dispatcher');
    7.  
    8. /**
    9.  * Bs model.
    10.  */
    11. class BsModelOffice extends JModelForm
    12. {
    13.    
    14.     var $_item = null;
    15.    
    16.     /**
    17.      * Method to auto-populate the model state.
    18.      *
    19.      * Note. Calling getState in this method will result in recursion.
    20.      *
    21.      * @since   1.6
    22.      */
    23.     protected function populateState()
    24.     {
    25.         $app = JFactory::getApplication('com_bs');
    26.  
    27.         // Load state from the request userState on edit or from the passed variable on default
    28.         if (JFactory::getApplication()->input->get('layout') == 'edit') {
    29.             $id = JFactory::getApplication()->getUserState('com_bs.edit.office.id');
    30.         } else {
    31.             $id = JFactory::getApplication()->input->get('id');
    32.             JFactory::getApplication()->setUserState('com_bs.edit.office.id', $id);
    33.         }
    34.         $this->setState('office.id', $id);
    35.  
    36.         // Load the parameters.
    37.         $params = $app->getParams();
    38.         $params_array = $params->toArray();
    39.         if(isset($params_array['item_id'])){
    40.             $this->setState('office.id', $params_array['item_id']);
    41.         }
    42.         $this->setState('params', $params);
    43.  
    44.     }
    45.        
    46.  
    47.     /**
    48.      * Method to get an ojbect.
    49.      *
    50.      * @param   integer The id of the object to get.
    51.      *
    52.      * @return  mixed   Object on success, false on failure.
    53.      */
    54.     public function &getData($id = null)
    55.     {
    56.         if ($this->_item === null)
    57.         {
    58.             $this->_item = false;
    59.  
    60.             if (empty($id)) {
    61.                 $id = $this->getState('office.id');
    62.             }
    63.  
    64.             // Get a level row instance.
    65.             $table = $this->getTable();
    66.  
    67.             // Attempt to load the row.
    68.             if ($table->load($id))
    69.             {
    70.                 // Check published state.
    71.                 if ($published = $this->getState('filter.published'))
    72.                 {
    73.                     if ($table->state != $published) {
    74.                         return $this->_item;
    75.                     }
    76.                 }
    77.  
    78.                 // Convert the JTable to a clean JObject.
    79.                 $properties = $table->getProperties(1);
    80.                 $this->_item = JArrayHelper::toObject($properties, 'JObject');
    81.             } elseif ($error = $table->getError()) {
    82.                 $this->setError($error);
    83.             }
    84.         }
    85.  
    86.         return $this->_item;
    87.     }
    88.    
    89.     public function getTable($type = 'Office', $prefix = 'BsTable', $config = array())
    90.     {  
    91.         $this->addTablePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
    92.         return JTable::getInstance($type, $prefix, $config);
    93.     }    
    94.  
    95.    
    96.     /**
    97.      * Method to check in an item.
    98.      *
    99.      * @param   integer     The id of the row to check out.
    100.      * @return  boolean     True on success, false on failure.
    101.      * @since   1.6
    102.      */
    103.     public function checkin($id = null)
    104.     {
    105.         // Get the id.
    106.         $id = (!empty($id)) ? $id : (int)$this->getState('office.id');
    107.  
    108.         if ($id) {
    109.            
    110.             // Initialise the table
    111.             $table = $this->getTable();
    112.  
    113.             // Attempt to check the row in.
    114.             if (method_exists($table, 'checkin')) {
    115.                 if (!$table->checkin($id)) {
    116.                     $this->setError($table->getError());
    117.                     return false;
    118.                 }
    119.             }
    120.         }
    121.  
    122.         return true;
    123.     }
    124.  
    125.     /**
    126.      * Method to check out an item for editing.
    127.      *
    128.      * @param   integer     The id of the row to check out.
    129.      * @return  boolean     True on success, false on failure.
    130.      * @since   1.6
    131.      */
    132.     public function checkout($id = null)
    133.     {
    134.         // Get the user id.
    135.         $id = (!empty($id)) ? $id : (int)$this->getState('office.id');
    136.  
    137.         if ($id) {
    138.            
    139.             // Initialise the table
    140.             $table = $this->getTable();
    141.  
    142.             // Get the current user object.
    143.             $user = JFactory::getUser();
    144.  
    145.             // Attempt to check the row out.
    146.             if (method_exists($table, 'checkout')) {
    147.                 if (!$table->checkout($user->get('id'), $id)) {
    148.                     $this->setError($table->getError());
    149.                     return false;
    150.                 }
    151.             }
    152.         }
    153.  
    154.         return true;
    155.     }    
    156.    
    157.     /**
    158.      * Method to get the profile form.
    159.      *
    160.      * The base form is loaded from XML
    161.      *
    162.      * @param   array   $data       An optional array of data for the form to interogate.
    163.      * @param   boolean $loadData   True if the form is to load its own data (default case), false if not.
    164.      * @return  JForm   A JForm object on success, false on failure
    165.      * @since   1.6
    166.      */
    167.     public function getForm($data = array(), $loadData = true)
    168.     {
    169.         // Get the form.
    170.         $form = $this->loadForm('com_bs.office', 'office', array('control' => 'jform', 'load_data' => $loadData));
    171.         if (empty($form)) {
    172.             return false;
    173.         }
    174.  
    175.         return $form;
    176.     }
    177.  
    178.     /**
    179.      * Method to get the data that should be injected in the form.
    180.      *
    181.      * @return  mixed   The data for the form.
    182.      * @since   1.6
    183.      */
    184.     protected function loadFormData()
    185.     {
    186.         $data = $this->getData();
    187.        
    188.         return $data;
    189.     }
    190.  
    191.     /**
    192.      * Method to save the form data.
    193.      *
    194.      * @param   array       The form data.
    195.      * @return  mixed       The user id on success, false on failure.
    196.      * @since   1.6
    197.      */
    198.     public function save($data)
    199.     {
    200.         $id = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('office.id');
    201.         $state = (!empty($data['state'])) ? 1 : 0;
    202.         $user = JFactory::getUser();
    203.  
    204.         if($id) {
    205.             //Check the user can edit this item
    206.             $authorised = $user->authorise('core.edit', 'com_bs') || $authorised = $user->authorise('core.edit.own', 'com_bs');
    207.             if($user->authorise('core.edit.state', 'com_bs') !== true && $state == 1){ //The user cannot edit the state of the item.
    208.                 $data['state'] = 0;
    209.             }
    210.         } else {
    211.             //Check the user can create new items in this section
    212.             $authorised = $user->authorise('core.create', 'com_bs');
    213.             if($user->authorise('core.edit.state', 'com_bs') !== true && $state == 1){ //The user cannot edit the state of the item.
    214.                 $data['state'] = 0;
    215.             }
    216.         }
    217.  
    218.         if ($authorised !== true) {
    219.             JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR'));
    220.             return false;
    221.         }
    222.        
    223.         $table = $this->getTable();
    224.         if ($table->save($data) === true) {
    225.             return $id;
    226.         } else {
    227.             return false;
    228.         }
    229.        
    230.     }
    231.    
    232.      function delete($data)
    233.     {
    234.         $id = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('office.id');
    235.         if(JFactory::getUser()->authorise('core.delete', 'com_bs') !== true){
    236.             JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR'));
    237.             return false;
    238.         }
    239.         $table = $this->getTable();
    240.         if ($table->delete($data['id']) === true) {
    241.             return $id;
    242.         } else {
    243.             return false;
    244.         }
    245.        
    246.         return true;
    247.     }
    248.    
    249.     function getCategoryName($id){
    250.         $db = JFactory::getDbo();
    251.         $query = $db->getQuery(true);
    252.         $query
    253.             ->select('title')
    254.             ->from('#__categories')
    255.             ->where('id = ' . $id);
    256.         $db->setQuery($query);
    257.         return $db->loadObject();
    258.     }
    259.    
    260. }



    \views\office\
    Код (PHP):
    1. defined('_JEXEC') or die;
    2.  
    3. jimport('joomla.application.component.view');
    4.  
    5. /**
    6.  * View to edit
    7.  */
    8. class BsViewOffice extends JView {
    9.  
    10.     protected $state;
    11.     protected $item;
    12.     protected $form;
    13.     protected $params;
    14.  
    15.     /**
    16.      * Display the view
    17.      */
    18.     public function display($tpl = null) {
    19.        
    20.         $app    = JFactory::getApplication();
    21.         $user       = JFactory::getUser();
    22.        
    23.         $this->state = $this->get('State');
    24.        
    25.  
    26.         $this->params = $app->getParams('com_bs');
    27.        
    28.  
    29.         // Check for errors.
    30.         if (count($errors = $this->get('Errors'))) {
    31.             throw new Exception(implode("\n", $errors));
    32.         }
    33.        
    34.        
    35.        
    36.         if($this->_layout == 'edit') {
    37.            
    38.             $authorised = $user->authorise('core.create', 'com_bs');
    39.  
    40.             if ($authorised !== true) {
    41.                 throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'));
    42.             }
    43.         }
    44.        
    45.         $this->_prepareDocument();
    46.  
    47.         parent::display($tpl);
    48.     }
    49.  
    50.  
    51.     /**
    52.      * Prepares the document
    53.      */
    54.     protected function _prepareDocument()
    55.     {
    56.         $app    = JFactory::getApplication();
    57.         $menus  = $app->getMenu();
    58.         $title  = null;
    59.  
    60.         // Because the application sets a default page title,
    61.         // we need to get it from the menu item itself
    62.         $menu = $menus->getActive();
    63.         if($menu)
    64.         {
    65.             $this->params->def('page_heading', $this->params->get('page_title', $menu->title));
    66.         } else {
    67.             $this->params->def('page_heading', JText::_('com_bs_DEFAULT_PAGE_TITLE'));
    68.         }
    69.         $title = $this->params->get('page_title', '');
    70.         if (empty($title)) {
    71.             $title = $app->getCfg('sitename');
    72.         }
    73.         elseif ($app->getCfg('sitename_pagetitles', 0) == 1) {
    74.             $title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title);
    75.         }
    76.         elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
    77.             $title = JText::sprintf('JPAGETITLE', $title, $app->getCfg('sitename'));
    78.         }
    79.         $this->document->setTitle($title);
    80.  
    81.         if ($this->params->get('menu-meta_description'))
    82.         {
    83.             $this->document->setDescription($this->params->get('menu-meta_description'));
    84.         }
    85.  
    86.         if ($this->params->get('menu-meta_keywords'))
    87.         {
    88.             $this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
    89.         }
    90.  
    91.         if ($this->params->get('robots'))
    92.         {
    93.             $this->document->setMetadata('robots', $this->params->get('robots'));
    94.         }
    95.     }        
    96.    
    97. }


    \views\office\tmpl\default.php
    Код (PHP):
    1. defined('_JEXEC') or die;
    2.  
    3. //Load admin language file
    4. $lang = JFactory::getLanguage();
    5. $lang->load('com_bs', JPATH_ADMINISTRATOR);
    6.  
    7. ?>
    8. <?php if ($this->item) : ?>
    9.  
    10.     <div class="item_fields">
    11.  
    12.         <ul class="fields_list">
    13.  
    14.            
    15.  
    16.         </ul>
    17.  
    18.     </div>
    19.    
    20. <?php
    21. else:
    22.     echo JText::_('COM_BS_ITEM_NOT_LOADED');
    23. endif;
    24. ?>
     
  2.  
  3. FeaMor
    Offline

    FeaMor Пользователь

    Регистрация:
    01.09.2008
    Сообщения:
    104
    Симпатии:
    2
    Пол:
    Мужской
    На сколько я понимаю, ходовыми переменными являются:
    | $state
    | $item
    | $form
    | $params
    они передаются туда сюда, что ли...

    Какие из них как мне надо использовать? Или их нельзя трогать?
     
  4. AKopytenko
    Offline

    AKopytenko Russian Joomla! Team Команда форума

    Регистрация:
    01.09.2011
    Сообщения:
    1 963
    Симпатии:
    168
    Пол:
    Мужской
    Если плаваешь в этой теме - напиши компонент не на MVC - в чём проблема?
    Почитай статьи по работе с базой в Joomla 2.5 и флаг тебе в руки...
     
  5. FeaMor
    Offline

    FeaMor Пользователь

    Регистрация:
    01.09.2008
    Сообщения:
    104
    Симпатии:
    2
    Пол:
    Мужской
    Ну я уж хочу использовать защиту джумлы в своем компоненте
    Я уже писал, но для ранних версий, а здесь ну наиусложненно как-то получилось ( не знаю какую функцию можно "вскрывать" (
    а простых генераторов компонента уже нигде нет
    вот и спрашиваю поэтому здесь, куда что я могу втыкнуть свое
     
  6. woojin
    Offline

    woojin Местный Команда форума => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской
    если путаешься и не знаешь зачем лишние файлы, удали их и исключи любое их упоминание из оставшихся файлов
    попробуй написать что тебе надо
    всё должно работать

    P.S. или бери самый маленький компонент и смотри как он работает, на его основе делай что тебе надо
     
  7. FeaMor
    Offline

    FeaMor Пользователь

    Регистрация:
    01.09.2008
    Сообщения:
    104
    Симпатии:
    2
    Пол:
    Мужской
    Да, я так и сделал )
    Взял прошлый свой компонент и переименовал все названия )
    хотя судя по xml, он вообще для joomla 1.7 )) ну и пусть, зато работает, там примитивные связи с БД и расчеты у меня ) и никаких items, forms не нужно
    а то в новосозданном компоненте ну слишком много всяких обработчиков, которые я не понимаю, но наверняка они и нужные...
     
  8. woojin
    Offline

    woojin Местный Команда форума => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской
    вообще то нужны
     
  9. FeaMor
    Offline

    FeaMor Пользователь

    Регистрация:
    01.09.2008
    Сообщения:
    104
    Симпатии:
    2
    Пол:
    Мужской
    а где хоть узнать что для чего нужно?
     
  10. woojin
    Offline

    woojin Местный Команда форума => Cпециалист <=

    Регистрация:
    31.05.2009
    Сообщения:
    3 206
    Симпатии:
    334
    Пол:
    Мужской
    только на joomla.org там где то ссылки на документацию есть
     

Поделиться этой страницей

Загрузка...