开发者

Kohana 3 module structure question

everybody! I have a new question about Kohana 3, or rather about a module structure. I develop a small module called Textblock. It's about an ordinary page or a small insertion to the site layout (e.g. a greeting or a slogan, company name). It contains both controllers and models. Models inherit Sprig_MPTT. And one feature I'd like to implement is one could be able to call this module like this:

$textblock = Textblock::get_single(1);      //by id
$children  = Textblock::get_children_of(4); //id of parent

and not

$textblock = Sprig::factory('Textblock')->get_single(1);
$children  = Sprig::factory('Textblock')->get_children_of(4);

Those methods are defined in Model_Textb开发者_StackOverflow社区lock class as static.

So, I made a wrapper class Textblock, that inherits Model_Textblock. What if I suddenly want change Sprig to Jelly, for example? Foreground won't change at all. Another advantage, imho, is more clarity for anyone, who wants to use this module (e.g. it could be another programmer in the team).

But there's a doubt if I'm on a wrong way... So, the question itself: is the suggested a right way to organize my module? Or it's preferable to keep ordinary Sprig::factory('Textblock') where Textblock's functionality is needed, remove additional wrapper class and remove static?


There is no need to extend Model_Textblock. You can create a model instance and call its method:

class Textblock {
   public static function get_single($id)
   {
      return Sprig::factory('textblock')->get_single($id);
   }
   // etc
}

But this way you should copy model methods in your static class (not DRY). Also, what if you have more than one model? All you want (as I understand) is to easily change AR driver. So I'd preffer this kind of class:

class Textblock {   

   // saved objects, dont create on model twice
   protected static $_instances = array();

   public static function model($name)
   {
      if (! isset(self::$_instances[$name]))
      {
          $model = Sprig_MPTT::factory($name);
          // you can add try..catch to prevent exceptions
          // or add another checks
          self::$_instances[$name] = $model;
      }
      return clone self::$_instances[$name];
   }
}

and use it like Textblock::model('textblock')->get_single($id).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜