RSS   Twitter   Copiny   Copiny
Нашел ошибку? 

Выдели фрагмент текста с ошибкой или неточностью и нажми Ctrl+Enter!

Создание MVC компонента Joomla 1.5 - Шаг 2, Добавляем Модель

Текст ниже основан на комопоненте view-controller для CMS Joomla 1.5. Для полного понимания статьи можно прочитать создание комопонета «Hello world», где в итоге получается простейший компонент приветствия, который можно считать образцом кода MVC. Он прост и фактически ничего не делает поэтому необходима модель, создание которой мы рассмотрим ниже.

Создание модели

Модель — часть компонента, которая предоставляет данные для вида по его запросу посланому через Контроллер. Такой метод часто освобождает от рутинной работы и от хаоса в коде, предоставляет возможность управлять данными удобным способом в дополнение к коду, который посылает запрос данных из Модели.

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

При подобной реализации вся обработка данных ложиться на модель и если вдруг случиться такое, что нам необходимо изменить источник данных с MySQL на RSS-ленту, то изменится только модель, не затрагивая всего остального кода — шаблона (он же Вид, Представление, View) и контроллер (controller).

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

В этом уроке, будем моделировать событие компонента «Hello», которое генерирует приветствие. Таким образом в компоненте будет один запрос к модели getGreeting(), который возвратит строку «Hello, World!».

Код модели для компонента "Hello Word"

<?php
/**
 * Hello Модель для "Hello" Компонета
 * 
 */


// Check to ensure this file is included in Joomla!
defined ('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

/**
 * Hello Model
 * @package    Автор
 * @subpackage Components
 */
class HelloModelHello extends JModel
{
    /**
    * Gets the greeting
    * @return string The greeting to be displayed to the user
    */
    function getGreeting()
    {
        return 'Hello, World!';
    }
}
?>

Строка, которая начинается с jimport - это функция используется, для подключения библиотек Joomla. В данном случае подгружается структура, которая требуются для нашего компонента. Этот специфический запрос загрузит файл

<корень сайта>/libraries/joomla/application/component/model.php

Точки "." используются как директивные слеши, и последняя часть - имя загружаемого файла. Таким образом можно загружать любые библиотеки из директории "libraries".

Это специфический файл содержит определение класса JModel, который является необходимым для нормальной работы модели компонента, поэтому наш класс должен его расширять.

Создав Модель, необходимо изменить Представление - добавить запрос к Модели для получения строки приветствия.

Используем Модель ( Model ) в Представление ( view )

Структура Joomla - организована таким способом, что контроллер автоматически загрузит модель, которая имеет то же название что и представление (view) и передаст доступ к своему классу. Так как Представление называется "Hello", модель "Hello" будет автоматически загружена и опубликована в Представление (view). Поэтому, мы можем легко объявить функцию класса модели, используя метод класса JView::getModel().

В код файла view.html.php вносим изменения. Заменяем строку:

$greeting = "Hello World!";

На строку

$model = $this->getModel();
$greeting = $model->getGreeting();

Так должен выглядеть итоговый код файла view.html.php:

<?php
/**
 * Hello View for Hello World Component
 * @package    	Автор
 * @subpackage 	Components
 * @link			components/views/hello/view.html.php
 * @license    	GNU/GPL
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.view');

/**
 * HTML View class for the HelloWorld Component
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class HelloViewHello extends JView
{
    function display($tpl = null)
    {
        $model = $this->getModel();
        $greeting = $model->getGreeting();
        $this->assignRef( 'greeting', $greeting );
        parent::display($tpl);
    }
}
?>

Добавление для файла hello.xml

В завершение работы над данной версией компонента, необходима в секцию Site (Front End) добавить файлы Модели:

<filename>models/hello.php</filename>

В итоге мы имеем простой MVC-компонент. Каждый элемент очень прост, но в целом компонент уже обладает более большей гибкостью и возможностью.

Прикрепленные файлы:
Компонент Joomla 1.5 Hello world, с моделью
Объем: 5.09 KB; Тип: zip; Загрузок: 1454; в сутки: ~0; Обновлен: 16:19, 24 Июля 2011;
Смотрите также:
Комментарии (45) Добавить комментарий
  • Владимир
    Владимир
    19 Ноября 2011, 01:36
     ↑  +8  ↓     ответ

    Что за постоянный плагиат, куча сайтов и на всех один и тот же пример!!! Вот и кому это может быть интересно! Напишите что-нибудь уже своё, если у Вас есть знания в программировании

    • Рейкбек
      Рейкбек
      02 Октября 2012, 17:53
       ↑  -4  ↓     ответ

      не нравится, не читайте, ищите уникальное или пишите свое, когда разберетесь.

  • Alex
    Alex
    20 Ноября 2012, 11:32
     ↑  0  ↓     ответ

    В тексте не указано, что файл модели нужно назвать hello.php и вложить в новую папку models папки компонента фронт-енда. Без прикрепленного файла непонятна файловая структура получившихся изменений.

  • Vit
    Vit
    15 Марта 2013, 20:06
     ↑  0  ↓     ответ

    Спасибо, очень хорошее описание, еще хотелось бы материал в котором рассказывается, как это все упаковывать следует

  • Сергей
    Сергей
    13 Мая 2014, 18:10
     ↑  0  ↓     ответ

    Спасибо отличная статья. Пока что все доходчиво. Даже разобрался что 'greeting' можно изменить например на myVar и потом в шаблоне вызвать например так <?php echo $this->myVar ; ?>, можно так же передавать несколько таких переменных связанных с функциями в модели.

    Спасибо ребята отличный проект

  • tinyurl.com
    tinyurl.com
    25 Ноября 2019, 01:31
     ↑  0  ↓     ответ

    Hi there mates, how is all, and what you wish for to say concerning this article, in my view its in fact awesome designed for me.

  • coconut oil for
    coconut oil for
    26 Ноября 2019, 03:32
     ↑  0  ↓     ответ

    Good way of explaining, and fastidious paragraph to obtain information on the topic of my presentation subject matter,

    which i am going to convey in academy.

  • plenty of fish dating site
    plenty of fish dating site
    26 Ноября 2019, 18:33
     ↑  0  ↓     ответ

    Hey! Do you know if they make any plugins to safeguard

    against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any suggestions?

  • generic cialis for sale
    generic cialis for sale
    22 Июля 2021, 07:24
     ↑  0  ↓     ответ

    If some one needs expert view about blogging afterward i propose him/her

    to visit this webpage, Keep up the pleasant work.

  • cheap cialis
    cheap cialis
    01 Января 2022, 18:46
     ↑  0  ↓     ответ

    Hey there this is kinda of off topic but I was

    wanting to know if blogs use WYSIWYG editors or if you have to manually

    code with HTML. I'm starting a blog soon but have no coding knowledge so

    I wanted to get advice from someone with experience. Any help would be enormously appreciated!

  • http://tinyurl.com/y76o55o7
    http://tinyurl.com/y76o55o7
    26 Марта 2022, 11:52
     ↑  0  ↓     ответ

    I have read so many articles or reviews regarding the blogger lovers except this paragraph is really a good post, keep it

    up.

  • tinyurl.com
    tinyurl.com
    27 Марта 2022, 03:31
     ↑  0  ↓     ответ

    It is not my first time to pay a quick visit this web site,

    i am visiting this web page dailly and get fastidious

    data from here everyday.

  • tinyurl.com
    tinyurl.com
    31 Марта 2022, 04:33
     ↑  0  ↓     ответ

    What i do not understood is if truth be told how you

    are not actually much more neatly-preferred than you may be right now.

    You are very intelligent. You recognize therefore considerably when it comes

    to this topic, produced me for my part consider it from numerous various angles.

    Its like women and men don't seem to be involved except

    it's something to accomplish with Lady gaga! Your own stuffs great.

    All the time handle it up!

  • how to find the cheapest flights
    how to find the cheapest flights
    03 Апреля 2022, 01:03
     ↑  0  ↓     ответ

    I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed

    about my problem. You're incredible! Thanks!

  • cheap flights tickets
    cheap flights tickets
    04 Апреля 2022, 23:40
     ↑  0  ↓     ответ

    Amazing! This blog looks just like my old one!

    It's on a totally different topic but it has pretty much

    the same layout and design. Outstanding choice of

    colors!

  • airtickets
    airtickets
    05 Апреля 2022, 02:34
     ↑  0  ↓     ответ

    Hey there! I've been following your website for a while now and finally got

    the bravery to go ahead and give you a shout out from Porter Texas!

    Just wanted to mention keep up the good work!

  • air ticket
    air ticket
    05 Апреля 2022, 21:50
     ↑  0  ↓     ответ

    Attractive component of content. I simply stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts.

    Anyway I will be subscribing on your augment or even I fulfillment you

    access consistently fast.

  • cheap flight tickets
    cheap flight tickets
    06 Апреля 2022, 09:31
     ↑  0  ↓     ответ

    We're a group of volunteers and starting a new scheme in our community.

    Your website offered us with valuable info to work on. You have done a formidable job and our whole community will be thankful to you.

  • discount airline tickets
    discount airline tickets
    06 Апреля 2022, 21:43
     ↑  0  ↓     ответ

    This website was... how do I say it? Relevant!! Finally I've found

    something that helped me. Thanks a lot!

  • gamefly
    gamefly
    07 Апреля 2022, 13:27
     ↑  0  ↓     ответ

    Hi, I do think this is a great website. I stumbledupon it ;) I will revisit once again since i have book-marked it.

    Money and freedom is the greatest way to change,

    may you be rich and continue to help other people.

  • gamefly
    gamefly
    10 Апреля 2022, 21:30
     ↑  0  ↓     ответ

    you're really a just right webmaster. The site loading speed is amazing.

    It kind of feels that you're doing any unique trick. In addition, The contents are masterwork.

    you've done a wonderful process on this subject!

  • http://tinyurl.com/y6jbphjt
    http://tinyurl.com/y6jbphjt
    10 Мая 2022, 08:47
     ↑  0  ↓     ответ

    Howdy would you mind letting me know which webhost you're utilizing?

    I've loaded your blog in 3 different internet browsers and I

    must say this blog loads a lot faster then most. Can you suggest a good hosting provider

    at a reasonable price? Thank you, I appreciate it!

  • http://tinyurl.com
    http://tinyurl.com
    11 Мая 2022, 20:15
     ↑  0  ↓     ответ

    Saved as a favorite, I like your site!

  • t.co
    t.co
    05 Июня 2022, 13:47
     ↑  0  ↓     ответ

    Great blog here! Also your site loads up very fast!

    What web host are you using? Can I get your affiliate

    link to your host? I wish my site loaded up as quickly as yours

    lol

  • tinyurl.com
    tinyurl.com
    07 Июля 2022, 09:57
     ↑  0  ↓     ответ

    Hi to all, the contents present at this web

    page are genuinely awesome for people knowledge, well, keep up the nice work fellows.

  • http://tinyurl.com/2e2g3apo
    http://tinyurl.com/2e2g3apo
    15 Июля 2022, 19:36
     ↑  0  ↓     ответ

    I'm not sure why but this site is loading very

    slow for me. Is anyone else having this issue or is it a problem

    on my end? I'll check back later on and see if the problem

    still exists.

  • t.co
    t.co
    22 Июля 2022, 19:49
     ↑  0  ↓     ответ

    Generally I do not learn article on blogs, however I

    would like to say that this write-up very pressured me to try and do so!

    Your writing style has been amazed me. Thank you, very great

    article.

  • tinyurl.com
    tinyurl.com
    28 Июля 2022, 07:20
     ↑  0  ↓     ответ

    That is a very good tip particularly to those fresh to the blogosphere.

    Simple but very precise info… Appreciate your sharing this one.

    A must read article!

  • tinyurl.com
    tinyurl.com
    29 Июля 2022, 05:04
     ↑  0  ↓     ответ

    I was able to find good information from your blog articles.

  • tinyurl.com
    tinyurl.com
    02 Августа 2022, 07:41
     ↑  0  ↓     ответ

    I just couldn't leave your web site prior to suggesting that I extremely enjoyed the usual information a person provide in your guests?

    Is gonna be again often to check up on new posts

  • http://tinyurl.com/24fny8cv
    http://tinyurl.com/24fny8cv
    03 Августа 2022, 05:00
     ↑  0  ↓     ответ

    Good web site you've got here.. It's difficult to find quality writing like yours nowadays.

    I honestly appreciate people like you! Take care!!

  • directory.uohyd.ac.in
    directory.uohyd.ac.in
    08 Августа 2022, 00:50
     ↑  0  ↓     ответ

    Oh my goodness! Awesome article dude! Many thanks, However I

    am having troubles with your RSS. I don't understand the reason why I

    am unable to subscribe to it. Is there anyone else having the same RSS problems?

    Anyone that knows the answer can you kindly respond? Thanks!!

  • tinyurl.com
    tinyurl.com
    08 Августа 2022, 10:23
     ↑  0  ↓     ответ

    Wonderful blog! I found it while browsing on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?

    I've been trying for a while but I never seem to get there!

    Appreciate it

  • www.kalpnatayal.com
    www.kalpnatayal.com
    09 Августа 2022, 20:03
     ↑  0  ↓     ответ

    Hi, yeah this paragraph is in fact fastidious and I have learned lot of things from

    it on the topic of blogging. thanks.

  • http://tinyurl.com
    http://tinyurl.com
    10 Августа 2022, 07:58
     ↑  0  ↓     ответ

    Useful information. Fortunate me I discovered your site unintentionally, and I'm shocked why this coincidence did not

    took place earlier! I bookmarked it.

  • coupon
    coupon
    12 Августа 2022, 02:51
     ↑  0  ↓     ответ

    Hi there, I think your blog could be having browser compatibility issues.

    Whenever I look at your site in Safari, it looks fine but when opening in I.E.,

    it has some overlapping issues. I simply wanted to provide you with a quick heads

    up! Other than that, great website!

  • http://tinyurl.com
    http://tinyurl.com
    12 Августа 2022, 20:39
     ↑  0  ↓     ответ

    Fantastic website you have here but I was curious

    about if you knew of any message boards that cover the same topics

    talked about here? I'd really like to be a part of

    community where I can get advice from other experienced individuals that share the same interest.

    If you have any suggestions, please let me know. Thanks!

  • tinyurl.com
    tinyurl.com
    13 Августа 2022, 16:09
     ↑  0  ↓     ответ

    What's up everyone, it's my first pay a visit at this web page, and piece of

    writing is really fruitful designed for me, keep up posting these types of content.

  • http://tinyurl.com/
    http://tinyurl.com/
    15 Августа 2022, 08:36
     ↑  0  ↓     ответ

    I am curious to find out what blog platform you're working with?

    I'm having some small security problems with my latest website and I would like to find something more risk-free.

    Do you have any solutions?

  • tracfone coupon
    tracfone coupon
    27 Ноября 2022, 08:45
     ↑  0  ↓     ответ

    I am not sure where you are getting your

    info, but great topic. I needs to spend some time

    learning much more or understanding more. Thanks for excellent information I was looking for

    this information for my mission.

  • tracfone 2022
    tracfone 2022
    30 Ноября 2022, 10:00
     ↑  0  ↓     ответ

    Great blog here! Additionally your website rather a lot up very fast!

    What web host are you the use of? Can I am getting your affiliate hyperlink on your host?

    I desire my website loaded up as fast as yours lol

  • coupon
    coupon
    01 Декабря 2022, 01:19
     ↑  0  ↓     ответ

    I'm really impressed with your writing skills and also

    with the layout on your weblog. Is this a paid theme

    or did you customize it yourself? Anyway keep up the nice quality

    writing, it's rare to see a great blog like this one today.

  • nursing assignment help
    nursing assignment help
    02 Декабря 2022, 06:51
     ↑  0  ↓     ответ

    W? are an on-line scholastic aid providing site.

    We have takеn a pledge to offer nursing essaу help to the trainees hai?ing from UK, UA?,

    USA, Singapo?e, Austrаlia and аlso New Zеaland.We

    have actually qualified writers from the nursing departments of the reputed

    est?blishments that can ?rite your nursing files.

    We have been provіding on the internet nursіng ?ob assistance for several ye?rs аs well as makіng a considerab?e differenhce in the trainee's nuгsіng

    job.

  • Lizzie
    Lizzie
    20 Января 2023, 11:09
     ↑  0  ↓     ответ

    Dear joomla-book.ru Administrator, similar in this article: <a href="/ 695example695.com " rel="nofollow">Link Text</a>

  • Saul
    Saul
    28 Января 2023, 06:41
     ↑  0  ↓     ответ

    Dear joomla-book.ru webmaster, Your posts are always well researched and well written.

Оставить комментарий




* обязательно для заполнения

1 введенный почтовый адрес используется только для обратной связи при ответах в комментариях и сервиса gravatar.com
.