开发者

Ways to design plugin

开发者 https://www.devze.com 2023-04-05 13:37 出处:网络
I designed two forms of plugin for my CMS but I have problem with one of them. The first one which will be implemented in the templates, it\'s cool there is no problem with that. But the second one wh

I designed two forms of plugin for my CMS but I have problem with one of them. The first one which will be implemented in the templates, it's cool there is no problem with that. But the second one which is for my admin area, I designed it in this way.

First I defined an instruction file which is a text file with this content:

REPLACE_INLINE("sample.php","//Echo/*","//Echo*/","echo \"test\"","ec开发者_运维百科ho \"new test\"");

In my plugin install function I split up these arguments and I go to do them and at last I save the new content. It works fine but I want to know, is it the right way of designing plugins? I think It's not and for that I posted a topic.

By the way my sample.php file which I assume that It's one of my CMS's source files contains this data:

<?php
  function showText(){
    //Echo/*
    echo "test";
    //Echo*/
  }
?>

And one thing else, If I do this, maybe next time another plugin wants to interact some data with the echo "test"; line And if it wouldn't be like the main template then we're gonna boom ! crash.

The sample.php data after plugin installation:

<?php
  function showText(){
    //Echo/*
    echo "new test";
    //Echo*/
  }
?>


Instead of having to textually replace content, you should either go with an object-oriented architecture where subclasses can overwrite showText (and/or call the old implementation) or use callbacks, like this:

$plugin_callbacks = array();
function showText() {
  $text = 'test';
  foreach ($plugin_callbacks as $cb) {
    $text = call_user_func($cb, $text);
  }
  echo $text;
}

$plugin_callbacks[] = function($text) {
  return 'new text';
}
$plugin_callbacks[] = function ($text) {
  return '<b>' . $text . '</b>';
};

However, as you can see, this can get messy soon. Therefore, unless there is a very limited number of callbacks, use an object-oriented design (which will require you to have an instantiation factory where plugins can register and determine which type the echoObject will be).


A much more organized way would be to go Object Oriented. For instance, build an abstract Plugin base class and extend that in your plugins.

For your admin area, you can create an AdminPlugin with some additional requirements and/or added base functionality. Like a getText() function, which would return the text (you're admin area should ultimately render it).

You can also include dependency management in your objects, to prevent a crash like you described.

0

精彩评论

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

关注公众号