开发者

Design Pattern with Javascript and PHP

开发者 https://www.devze.com 2023-03-29 22:34 出处:网络
i\'m creating a website in PHP, that has Javascript elements as well. This one, will be having what is like a plugin system where a plugin can be dynamically added to the website.

i'm creating a website in PHP, that has Javascript elements as well. This one, will be having what is like a plugin system where a plugin can be dynamically added to the website.

I've created the plugin system, but i don't like certain elements of the design. In particular, i'm using an MVC pattern, but there is a problem with javascript abstraction.

I have a certain file that loads all the plugins. Then, there is a javascript file that dynamically adds boxes to a window, depending on the selection that was made, for what plugin should be used.

It goes like this in a js file :

 if (SelValue == 'image_list')
   image_list(form_name, new_div, parent_div);

 if (SelValue == 'multiple_columns')
   multiple_columns(form_name, new_div, parent_div);

Then, right below, follows the declaration of imagelist() and so on. Of course, this is pretty cumbersome and c开发者_开发知识库ertainly does not look like a good practice. I would like to have all of these abstracted and isolated, so that a plugin is just a simple step to add to my code, if possible.

Do you know of any design pattern or practice that could fit this scenario ?


You could create a Object holding all functions like image_list and multiple_columns. Using those would look like:

plugins[SelValue](form_name, new_div, parent_div);

Adding a new function would look like this:

plugins.image_list = function (form_name, new_div, parent_div) {
    /* … */
}

This definition could go in a different file. Is that what you meant?

Edit: Pretty single-file version:

plugins = {
    image_list: function (form_name, new_div, parent_div) {
        /* … */
    },
    multiple_columns: function (form_name, new_div, parent_div) {
        /* … */
    },
};
plugins[SelValue](form_name, new_div, parent_div);


If you're not going to have more than 2 IF statements, that would be sufficient. However, if you're going to be extending it (or could foresee it expanding), then I would suggest using a Factory/Command design pattern. Implementation details would include a table or a dictionary to replace the multiple IF-statements that you would have.


The module pattern would probably fit your needs very well. This pattern basically would treat each "plugin" as a module, which itself should be fully functional and independent. Then you have a module loader/controller, which is responsible for loading the correct modules, and enabling modules to communicate with each other.

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

http://www.yuiblog.com/blog/2007/06/12/module-pattern/

0

精彩评论

暂无评论...
验证码 换一张
取 消