Выдели фрагмент текста с ошибкой или неточностью и нажми Ctrl+Enter!
Выдели фрагмент текста с ошибкой или неточностью и нажми Ctrl+Enter!
В первых двух уроках научились строить простой Model-View-Controller компонент. В итоге в компоненте есть одно Представление (View), которое получает данные от Модели, созданной в
Будет продемонстрировано, как использовать JDatabase класс для работы с базой данных.
Наша модель в настоящее время имеет один метод: getGreeting(). Этот метод очень прост — все, что эта функция делает — возвращение жестко-закодированное (hardcode) приветствие.
Для работы с базой данных, загрузим приветствие в таблицу базы данных. При установке компонента необходимо создание таблицы с записью текстового поля с приветствием. Как создать SQL файл и какие строки добавить в hello.xml, рассмотрим позже.
Для начала заменим код в Модели для получения приветствия с таблицы базы данных.
В первую очередь нужно подключится к базе данных. В Joomla 1.5 все параметры для подключения уже есть и для того чтобы создать свое используем следующее:
JFactory — статический класс, который используется, чтобы подключится к многим объектам системы. Подробней информацию об этом классе можно посмотреть в документации API.
Чтобы получить доступ к глобальному объекту базы данных используем метод getDBO().
Важное замечание: Joomla подключается к базе данных самостоятельно и один раз во время запуска фреймворка, при использовании getDBO(), мы просто получим ссылку на объект базы данных.
Сохраняем запрос для получения объекта базы данных. Для этого вносим изменения в функции Модели getGreeting(), находящей в файле:
/components/com_hello/model/models/hello.php$db->loadResult() метод выполнит запрос к базе данных, который был установлен строкой выше через setQuery() и вернет полученный объект.
Joomla инсталлятор имеет встроенную поддержку выполнения запросов SQL в процессе установки компонента. Эти запросы должны быть сохранены в стандартном install.sql файле.
Для инсталляционного файла SQL используем три запроса:
Ниже все три запроса для инсталляционного файла:
Joomla сама заменит "#__ " на префикс таблицы текущей базы данных MySQL, исходя из текущих настроек. В первом запросе уничтожается таблица #__hello, это необходима для того, чтобы не было накладок при повторных установках одного и тоже компонента.
По второму запросу создается два поля в таблице.
Сохраняем эти запросы в файле install.sql и переносим его в дистрибутив компонента:
com_hello/admin/install.sql.При деинсталляции компонента необходимо удалять таблицы, которые были созданы установкой, но при этом нужно всегда учитывать, то что пользователь может случайно удалить компонент. Для того чтобы он таким образом не удалил свои данные в таблицах базы данных, необходимо требовать подтверждение такого действия:
Сохраняем этот запрос в файле uninstall.sql и переносим его в дистрибутив компонента:
com_hello/admin/uninstall.sql.Прежде чем указывать какие файлы использовать при установке и деинсталляции для запуска SQL запросов, нужно указать куда копировать эти файлы. Оба файла должны находится в корне папки административной части компонента. Далее, указываем инсталлятору какие файлы использовать для SQL запроса при установке и деинсталляции компонента.
Новый код для инсталляционного XML файла:
При установке и деинсталляции может быть два значения у атрибута charset, первый — «utf8» и если версия MySQL сервера не поддерживает кодировку utf8 указывается атрибут «non-utf8»
Атрибут driver пока может иметь только одно значение — «mysql». В дальнейшем планируется расширить возможности Joomla 1.5 для работы с разными базами данных.
Теперь компонент «Hello» может работать не только с MVC framework классами, но и с классами запросов JDatabase. Вы уже можете создавать компоненты работающее по технологии MVC с использованием таблиц базы данных, указывая их параметры инсталлятору
Здравствуйте! Я столкнулся с такой проблемой. Есть таблица с полями и я добавил туда ещё несколько полей. Некоторые добавил уже давненько, а некоторые недавно. В админке, в каталоге tables компонента прописал названия новых полей. Делаю запрос на доставание всех полей и у меня те, которые добавил недавно, не достаются. В чём может быть проблема? Joomla кэширует метаданные таблиц?
А можно как-то подробнее про структуру таблиц, полей и сам запрос ?
Спасибо, но я уже разобрался. Неправильно подключал внешний файл.
Пропущено: в xml для инстала и удаления необходио тоже подключить эти файлы:
<administration>
<files folder="admin">
...
<filename>install.sql</filename>
<filename>uninstall.sql</filename>
</files>
</administration>
Здравствуйте! у меня проблема, загрузила на сайт joomla 1.5.24 зашла на сайт начала автоматическую установку джумлы ввела базу данных а мне всё равно выдаёт ошибку : Не могу подключиться к базе данных. Номер ошибки: Unable to connect to the database:Could not connect to MySQL. если иная причина почему это происходит, введённые данные все правильные. Заранее благодарю!
I've been browsing online more than 2 hours today, yet I never found any interesting article like yours.
It's pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did,
the web will be much more useful than ever before.
Its such as you read my thoughts! You appear
to know so much approximately this, such as you wrote the e-book in it or something.
I feel that you simply could do with a few p.c.
to pressure the message house a little bit, but instead of
that, that is great blog. An excellent read.
I'll certainly be back.
I am really glad to glance at this weblog posts which carries lots of helpful facts, thanks for
providing such data.
My family members all the time say that I am killing my
time here at net, but I know I am getting knowledge all the time by reading such
fastidious articles.
That is very fascinating, You're an overly professional blogger.
I've joined your feed and stay up for seeking more of your fantastic post.
Also, I have shared your website in my social networks
Hi there, I desire to subscribe for this website to take hottest updates,
thus where can i do it please assist.
Hi! I'm at work browsing your blog from my
new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts!
Carry on the superb work!
Touche. Outstanding arguments. Keep up the good effort.
Greetings! Very useful advice within this article!
It is the little changes that produce the most important changes.
Thanks a lot for sharing!
Hey There. I found your blog using msn. This is a very well written article.
I'll make sure to bookmark it and come back to read more of your useful info.
Thanks for the post. I will definitely comeback.
This web site definitely has all the information and
facts I wanted concerning this subject and didn't know who to ask.
Having read this I believed it was rather enlightening.
I appreciate you finding the time and energy to put
this short article together. I once again find myself spending a significant amount of time
both reading and commenting. But so what, it was still worth it!
Hello, everything is going nicely here and ofcourse every one is sharing
facts, that's truly good, keep up writing.
Aw, this was a very good post. Finding the time and actual effort to make a really
good article… but what can I say… I hesitate a whole lot and never manage to get anything done.
Have you ever considered writing an ebook or guest authoring on other blogs?
I have a blog based on the same subjects you discuss and would really like to
have you share some stories/information. I know my audience would appreciate your work.
If you're even remotely interested, feel free to shoot me an e
mail.
Good day! Would you mind if I share your blog with my facebook group?
There's a lot of folks that I think would really appreciate your content.
Please let me know. Many thanks
Heya i am for the first time here. I came across this board and
I find It truly useful & it helped me out a lot.
I hope to give something back and aid others
like you aided me.
Thank you for the good writeup. It in fact was
a amusement account it. Look advanced to more added agreeable from
you! However, how could we communicate?
Good post however I was wanting to know if you could
write a litte more on this subject? I'd be very grateful if you
could elaborate a little bit further. Bless
you!
continuously i used to read smaller articles that as well clear their motive,
and that is also happening with this article which I am reading now.
Asking questions are truly nice thing if you are not understanding anything entirely,
however this paragraph provides pleasant understanding even.
I blog often and I really appreciate your content. This article has really peaked my interest.
I will book mark your website and keep checking for new details about
once a week. I subscribed to your RSS feed as well.
Hello there! This is my first visit to your blog!
We are a team of volunteers and starting a new initiative in a community in the same niche.
Your blog provided us useful information to work on. You have done a extraordinary job!
Hello! I'm at work surfing around your blog from my new iphone 4!
Just wanted to say I love reading your blog and look forward to all your posts!
Keep up the fantastic work!
After looking over a handful of the blog articles on your web site,
I honestly appreciate your way of writing a blog.
I saved as a favorite it to my bookmark webpage list
and will be checking back soon. Please check out my website too and let me know
how you feel.
When someone writes an piece of writing he/she retains the thought of a user in his/her brain that how a user can be aware of it.
So that's why this post is outstdanding. Thanks!
Very good post. I'm going through some of these issues as
well..
With havin so much content do you ever run into any problems of plagorism or copyright
violation? My website has a lot of exclusive content I've either created myself
or outsourced but it seems a lot of it is popping it up all
over the internet without my authorization. Do you know any ways to
help reduce content from being ripped off? I'd genuinely appreciate
it.
Thanks very interesting blog!
It's impressive that you are getting ideas from
this piece of writing as well as from our argument made at this place.
Hello! Someone in my Myspace group shared this site with us so I came to look it over.
I'm definitely enjoying the information. I'm bookmarking and will
be tweeting this to my followers! Exceptional blog and terrific style and design.
What's up, this weekend is good in support of me, since this occasion i am reading this impressive
educational paragraph here at my house.
Greetings! I know this is kinda off topic but I was wondering if you knew where I could get a captcha plugin for
my comment form? I'm using the same blog platform as yours
and I'm having problems finding one? Thanks a lot!
I blog often and I truly thank you for your content. This article has truly peaked my interest.
I will take a note of your site and keep checking for new details about once a week.
I opted in for your Feed too.
This piece of writing will assist the internet viewers for setting up new weblog or
even a weblog from start to end.
Terrific work! This is the kind of information that are
supposed to be shared around the web. Shame on Google for no longer
positioning this put up higher! Come on over and talk over with my website .
Thank you =)
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 wonderful information I was looking for this info for my mission.
Have you ever thought about writing an ebook or guest authoring on other blogs?
I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I know my viewers would enjoy your
work. If you are even remotely interested, feel free to send me an e mail.
Nice post. I learn something new and challenging on sites I stumbleupon everyday.
It's always exciting to read through articles from other writers and practice something
from other sites.
Pretty component of content. I just stumbled upon your
blog and in accession capital to assert that I acquire in fact enjoyed
account your weblog posts. Any way I'll be subscribing on your feeds or even I achievement you get
right of entry to persistently fast.
This design is spectacular! You most certainly know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to
start my own blog (well, almost...HaHa!) Excellent job.
I really enjoyed what you had to say, and more than that, how you
presented it. Too cool!
Have you ever considered about including a little bit more than just your articles?
I mean, what you say is important and everything. Nevertheless think about if you added some great photos or
videos to give your posts more, "pop"! Your content is excellent but with images and videos, this site could certainly be one of the best in its field.
Great blog!
This piece of writing will help the internet people for setting up new weblog
or even a blog from start to end.
It's perfect time to make some plans for
the long run and it's time to be happy. I've learn this submit
and if I could I wish to suggest you some interesting things or advice.
Maybe you could write next articles referring to this article.
I want to learn even more issues about it!