在MVC中放置逻辑的正确位置 [英] Proper place to put logic in MVC

查看:82
本文介绍了在MVC中放置逻辑的正确位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用yii框架编写一个mvc Web应用程序.我有一些业务逻辑,不确定将其放置在何处. $usernameid=$model->random_id_gen('5');是我正在谈论的功能.

I'm writing an mvc web app with the yii framework. I have a piece of business logic and I'm unsure where to place it. $usernameid=$model->random_id_gen('5'); is the function I'm talking about.

SiteController:

SiteController:

<!-- snip -->
      public function actionIndex()
       {
         $model = new Users();

         if (isset($_POST['Users'])) {
            //call the active record table model
            $model = new Users();

            //massively assign attributes
            $model->attributes=$_POST['Users'];

            //generate random userid
            $usernameid=$model->random_id_gen('5');


<!-- snip -->

用户活动记录类别:

 <!-- snip -->
  public function random_id_gen($length)
    {
        $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        $max = strlen($characters) - 1;
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[mt_rand(0, $max)];
        }

        return $string;
    }

我的问题:这个id生成器函数是否属于Active Record模型?应该在控制器中吗?既然它是业务逻辑",但应该与数据库无关吗?

My question: Does this id generator function belong in the Active record model? Should it be in the controller? Should it be in a separate model since it is "business logic", but has little to do with databases?

我正在尝试更好地避免膨胀"我的MVC类.提前谢谢大家.

I'm trying to get better at not "bloating" my MVC classes. Thanks ahead of time guys.

更新 我正在寻找yii特定的解决方案.如果有这样的约定,问题似乎已经发展为应该在yii中的哪个地方放置库".

UPDATE I'm looking for a yii specific solution. It seems the question has developed into "where should one put libraries in yii" if there is such a convention.

推荐答案

MVC应该重命名为MVCL ..即Model-View-Controller-Library.这些功能应放入单独的库系统中.

MVC should be renamed to MVCL .. that is Model-View-Controller-Library. These kind of functions should go into a separate system of libraries.

控制器应位于顶部.它具有两个主要功能:接受用户输入并协调其他元素(控制器/库/视图)以进行输出.传统上,Controller从模型询问数据.但是数据操作(最常见)应该由库中的函数完成.

Controller should be on the TOP. It has two major functions : accepting user input and coordinating other elemnts (controller / library/view) for output. traditionally, Controller asks data from the model. But data manipulation (most common) should be done by functions in the library.

对于最常见的操作,可能有两个级别的库,一个可能是复杂的(基于对象),而另一个则可能是简单的(基于全局函数).诸如剥离标签,使数据XML就绪,清理URL等之类的事情.整个系统都可以访问简单的函数库,而无需任何特定的库对象的实例化.

There could be two levels of libraries, one could be complex (object based) and other could be simple (global functions based) for the most common operations. Something like stripping out tags, OR making the data XML ready, cleaning an URL etc.. simple functions libraries can be accessed by the whole system without any instantiation of the a particular library object.

有道理吗?

这篇关于在MVC中放置逻辑的正确位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆