Введение в плагины Joomla, принцип работы
Кратко о плагинах и реализации событий в Joomla
рейтинг: 7.9/10, голосов: 11
В Joomla реализована очень мощная и гибкая система для обработки событий. Придерживаясь идеологии эффективного ООП реализована "система наблюдения (прослушивания)", которая реагирует на зарегистрированные события и выполняет какие либо функции. Проще говоря - они позволяют писать собственные расширения ядра Joomla, без его модификаций.
Реализация
Система событий базируется на двух классах
- JPlugin - наблюдаемый класс.
- JEventDispather - класс- наблюдатель.
/**
* JPlugin Class
*
* @package Joomla.Framework
* @subpackage Application
* @since 1.5
*/
class JPlugin extends JObserver
{
/**
* Constructor
*
* For php4 compatability we must not use the __constructor as a constructor for plugins
* because func_get_args ( void ) returns a copy of all passed arguments NOT references.
* This causes problems with cross-referencing necessary for the observer design pattern.
*
* @param object $subject The object to observe
* @since 1.5
*/
function JPlugin(& $subject)
{
parent::__construct($subject);
}
/**
* Method to map events to handler methods
*
* @access public
* @param array Arguments
* @return mixed Routine return value
* @since 1.1
*/
function update( &$args )
{
/*
* First lets get the event from the argument array. Next we will unset the
* event argument as it has no bearing on the method to handle the event.
*/
$event = $args['event'];
unset($args['event']);
/*
* If the method to handle an event exists, call it and return its return
* value. If it does not exist, return a boolean true.
*/
if (method_exists($this, $event)) {
return call_user_func_array(array($this, $event), $args);
} else {
return true;
}
}
}
Этот класс делает две очень важные вещи.
Первое - это конструктор класса, который создаст экземпляр родительского класса JObserver. Вот что происходит в нем:
// Регистрация наблюдателя
$subject->attach($this);
// Установка объекта наблюдения
$this->_subject = &$subject;
Вторая важная вещь - это метод update. Метод получает массив из триггера, который содержит в себе два элемента - название события и список аргументов. После того как был вызван update, информация о названии события извлекается в отдельную переменную и удаляется, далее вызывается метод "event", в который передаются все параметры. В итоге Update - это ответ из self::$event($args);
Пример стороннего плагина
jimport('joomla.plugin');
/**
* Example Plugin
*/
class ExamplePlugin extends JPlugin
{
/**
* Обязательный конструктор класса
*/
function ExamplePlugin( &$subject ) {
parent::__construct( $subject );
}
/**
* Этот метод является обработчиком для события onIncrement.
* Он получает в виде аргумента целое число и делает инкремент (+1).
*/
function onIncrement($input)
{
return $input++;
}
}
Как видно, плагин сделать очень просто - достаточно правильно расширить класс JPlugin и описать обработку событий в виде методов.
My partner and I stumbled over here coming from a different website and
thought I should check things out. I like what I see so now i'm following you.
Look forward to checking out your web page for a second time.
Helpful information. Fortunate me I discovered your
site accidentally, and I am shocked why this twist of fate
didn't took place earlier! I bookmarked it.
Hello my family member! I want to say that this article is awesome, great written and come with almost all important infos.
I'd like to peer extra posts like this .
Thanks designed for sharing such a fastidious thinking, piece of
writing is pleasant, thats why i have read it fully
I am actually delighted to read this weblog posts which carries lots of helpful facts, thanks for
providing these kinds of data.
Appreciating the dedication you put into your website and detailed information you present.
It's great to come across a blog every once in a while
that isn't the same old rehashed information.
Fantastic read! I've bookmarked your site and I'm adding your RSS
feeds to my Google account.
Hi there, its good post concerning media print, we all know media is
a great source of facts.
Every weekend i used to pay a quick visit this web site, because
i wish for enjoyment, for the reason that this this
web site conations really nice funny material
too.
I am sure this piece of writing has touched all the internet viewers,
its really really pleasant post on building up new website.
My brother suggested I would possibly like this blog.
He used to be entirely right. This post truly made my day.
You cann't consider just how so much time I had spent for
this info! Thank you!
Hello There. I found your blog using msn. That is a really neatly written article.
I will make sure to bookmark it and come back to read
extra of your helpful info. Thank you for the post.
I'll definitely comeback.
Hi! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing a
few months of hard work due to no back up. Do you have any solutions to
prevent hackers?
What's up to all, how is all, I think every one
is getting more from this website, and your views are
good designed for new users.
magnificent points altogether, you simply won a logo new reader.
What could you recommend in regards to your post that you simply made
a few days ago? Any certain?
I do not even know how I finished up here, however I believed this post was once great.
I do not recognize who you're however definitely you're going to a famous blogger when you aren't already.
Cheers!
Hello, Neat post. There's a problem together with your web site in web explorer, may check this?
IE still is the marketplace chief and a large section of folks will leave out your wonderful writing due to this problem.
Attractive section of content. I just stumbled upon your
blog and in accession capital to assert that I get in fact enjoyed account your blog posts.
Anyway I will be subscribing to your feeds and even I achievement you access
consistently fast.
Ahaa, its good dialogue on the topic of this paragraph here at this blog, I have
read all that, so now me also commenting at this place.
This is my first time go to see at here and i am really happy to read all at single
place.
I pay a visit each day some web pages and blogs to read articles or reviews, however
this blog gives feature based writing.
You really make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand.
It seems too complex and very broad for me. I'm looking forward for your next post, I'll try to
get the hang of it!
I am extremely inspired along with your writing talents as smartly
as with the format in your blog. Is this a paid topic or did
you modify it your self? Either way stay up the nice quality writing, it's rare
to look a great weblog like this one these days..
When I originally commented I clicked the "Notify me when new comments are added" checkbox and
now each time a comment is added I get four e-mails with the same comment.
Is there any way you can remove people from that service?
Thanks a lot!
What's up to all, how is the whole thing, I think every one is getting more from
this web page, and your views are pleasant for new users.
What's up to every body, it's my first go to see of this webpage;
this webpage carries amazing and truly excellent material in support of visitors.
This is really interesting, You're a very skilled blogger.
I've joined your rss feed and look forward to seeking
more of your great post. Also, I have shared your site in my social networks!
Nice post. I learn something totally new and challenging on websites I stumbleupon everyday.
It will always be interesting to read through articles
from other authors and practice something from
other sites.
Magnificent site. Lots of useful info here. I am sending it to some pals ans also
sharing in delicious. And certainly, thanks for your effort!
I always spent my half an hour to read this webpage's articles or
reviews daily along with a mug of coffee.
Hi everyone, it's my first go to see at this website,
and paragraph is genuinely fruitful for me, keep up posting these types of content.
It's actually a nice and helpful piece of information. I'm glad that you simply
shared this useful info with us. Please keep us informed like this.
Thanks for sharing.
I know this if off topic but I'm looking into starting my own blog and was curious what all is needed to get setup?
I'm assuming having a blog like yours would cost a pretty penny?
I'm not very internet smart so I'm not 100% certain.
Any tips or advice would be greatly appreciated.
Appreciate it
Hello there! Would you mind if I share your blog with my myspace group?
There's a lot of people that I think would really enjoy your content.
Please let me know. Thanks
If you are going for finest contents like I do, just
visit this web site everyday as it offers feature contents, thanks
If some one needs to be updated with latest technologies
afterward he must be pay a visit this website and be up to date all the time.
Hey! Do you know if they make any plugins to protect against hackers?
I'm kinda paranoid about losing everything I've worked hard on. Any recommendations?
Magnificent site. Plenty of useful information here.
I am sending it to a few pals ans additionally sharing in delicious.
And certainly, thank you to your effort!
Please let me know if you're looking for a writer for your site.
You have some really great articles and I think I would be a good asset.
If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange
for a link back to mine. Please blast me an email if interested.
Thank you!
Greate post. Keep posting such kind of information on your
blog. Im really impressed by your blog.
Hi there, You have done an incredible job. I'll certainly digg it and personally recommend to my
friends. I'm sure they will be benefited from this site.
I read this paragraph completely regarding the comparison of latest and
preceding technologies, it's awesome article.
Hi, the whole thing is going sound here and ofcourse every one is sharing data, that's actually fine, keep
up writing.
Hi colleagues, how is everything, and what you want to say regarding this piece of
writing, in my view its really remarkable in support of
me.
Hey I know this is off topic but I was wondering if
you knew of any widgets I could add to my
blog that automatically tweet my newest twitter updates.
I've been looking for a plug-in like this for quite some time and was hoping maybe you would
have some experience with something like this. Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
Please let me know if you're looking for a author for your site.
You have some really great posts and I feel I would be a good asset.
If you ever want to take some of the load off, I'd love to write some content for your blog in exchange for a link back to mine.
Please send me an email if interested. Many thanks!
Hi there are using Wordpress for your blog platform?
I'm new to the blog world but I'm trying
to get started and set up my own. Do you need any html coding knowledge to make your own blog?
Any help would be really appreciated!
It's very straightforward to find out any topic on web as compared to books, as I found this piece of writing
at this web page.