【问题标题】:How should model interactions be with different controllers模型交互应该如何与不同的控制器
【发布时间】:2015-09-18 01:03:36
【问题描述】:

我有一个名为 Message 的模型,这是我网站中的一个内部通知。

我有一个控制器 RegistrationController 来处理新用户在我的网站上注册的情况。发生这种情况时,我会向所有用户发送Message

涉及的代码如下所示:

public static createMessage($receiver, $content)
{
    $message = new Message;
    $message->receiver = $receiver;
    $message->content = $content;
    $message->save(false);
}

RegistrationController.php中是这样调用的

   foreach($users as user)
       Message::createMessage($user->ID, $content);

什么是最好的方法并且不会违反 mvc?

  1. 在 Message 模型中,我添加了 createMessage() 函数。它不需要导入。

  2. 或者我创建一个MessageController 并在里面添加那个函数?如果我执行第 2 版,那么我需要在 RegistrationController 中输入 include MessageController

  3. 有更好的主意。

哪个版本会产生更好的代码并且可以更好地维护?请量化您的答案以避免意见。

【问题讨论】:

    标签: php model-view-controller yii model


    【解决方案1】:

    做 MVC 是一种编程风格。 在哪里放置逻辑没有限制。您可以将其放在模型或控制器中。

    哪一个最适合你的工作风格,使用它。

    我通常将通过接口与用户交互的逻辑放在Controller中。 (从接口获取值)

    并将有助于业务规则的逻辑放入模型中。 (用接口和数据库的值做事)

    如果您决定将 Message 逻辑作为 Controller,则不需要包含 MessageController。

    但请确保在 /config/main.php 中包含以下内容:

    'application.controllers.*'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2020-10-04
      • 2013-10-14
      相关资源
      最近更新 更多