【问题标题】:Kohana 3 module structure questionKohana 3模块结构题
【发布时间】:2010-09-05 14:35:58
【问题描述】:

大家!我有一个关于 Kohana 3 的新问题,或者更确切地说是关于模块结构的问题。我开发了一个名为 Textblock 的小模块。它是关于普通页面或站点布局的小插入(例如问候语或口号,公司名称)。它包含控制器和模型。模型继承 Sprig_MPTT。我想实现的一个功能是可以像这样调用这个模块:

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

而不是

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

这些方法在 Model_Textblock 类中定义为static

所以,我创建了一个包装类Textblock,它继承了Model_Textblock。例如,如果我突然想将 Sprig 更改为 Jelly 怎么办?前景根本不会改变。另一个优势,恕我直言,对于任何想要使用此模块的人来说都更加清晰(例如,它可能是团队中的另一位程序员)。

但是如果我走错了路,我会怀疑......所以,问题本身:建议的组织模块的正确方法是什么?或者最好在需要 Textblock 功能的地方保留普通的Sprig::factory('Textblock'),删除额外的包装类并删除static

【问题讨论】:

    标签: php kohana static-methods kohana-3


    【解决方案1】:

    无需扩展Model_Textblock。你可以创建一个模型实例并调用它的方法:

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

    但是这样你应该在你的静态类中复制模型方法(不是 DRY)。另外,如果您有多个模型怎么办?您想要的(据我所知)只是轻松更改 AR 驱动程序。所以我更喜欢这种课程:

    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];
       }
    }
    

    并像 Textblock::model('textblock')->get_single($id) 一样使用它。

    【讨论】:

    • 感谢您的评论。是的,我想让我的模块在任何地方都保持不变。我喜欢 Textblock 不继承 Model_Textblock 的想法,因为我认为模块必须为最终用户提供一组有限的方法,其中包含最必要的逻辑。你怎么看待这件事?还有不止一个模型:通常我每个实体都有一个模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多