2

In my current implementation of the MVC design pattern (demonstrated using PHP and CodeIgniter):

Let's say I have a "page" located at "www.mysite.com/blue/page" that is ultimately generated by the following (greatly simplified) files:

/libraries
    session_lib.php
/controllers
    /red
    /white
    /blue
        page.php
/models
    /red
    /white
    /blue
        funky_class.php
        page_model.php
/views
    /red
    /white
    /blue
        page.php

And here's an easy to understand controller:

// FILE: /controllers/blue/page.php

// Get some paramaters from URL
$params = $this->input->get();

// Use a library to do some stuff with these params with a session
$this->load->library('session_lib');
$this->session_lib->store_in_session($params);

// Use a very page specific class to do some funky stuff with the params
$this->load->model('blue/funky_class');
$funkified_params = $this->funky_class->funkify($params);

// Pass params to a model
$this->load->model('blue/page_model');
$data['output_from_db'] = $this->page_model->get_some_output_from_db($funkified_params);

// Send to view
$this->load->view('blue/page', $data);

And now the question...

What is the best procedure for these "funky" little page specific classes that don't interact with the database? In this example I store the little class with the models, and in some cases might just add additional methods inside the model class to do the funky stuff. Is this good practice? Or should the library and funky class both go inside the model so the controller is even skinnier (however the model might be used in other places without the need for sessions and funkiness)?

4

1 回答 1

2

我会使用一个助手。

  • 加载助手时,该函数将在全局范围内可用,因此您可以在任何地方调用它。
  • 它们非常适合小型、独立的函数,这些函数只做一件不一定与模型或库中的代码相关的事情
  • 当在一种或另一种格式之间转换内容(slugify、convert_timezone、change_query_string)或执行您不想考虑的小任务(force_ssl、is_image、uri_string)时,助手对我来说尤其出色

funkify() 似乎是一个合适的辅助函数,可以防止大量重复代码。

这是关于它们的 codeigniter 文档页面:http: //ellislab.com/codeigniter/user-guide/general/helpers.html

如果您处于辅助函数非常具体的情况,它只会在一个地方使用,您仍然可以使用辅助函数。page_helper.php例如,以您的控制器命名助手。

page_helper.php

function funkify($params) {
    // do funky stuff
    return $funky_params;
}

然后在你的控制器中:

class Page extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper('page');
    }

    public function page() {
        // do stuff
        $funky_params = funkify($params);
        // do more stuff
        $this->load->view('blue/page', $data);
    }

我没有任何借口,但有时如果我需要一个仅在一个位置(例如控制器)使用的剃须刀特定功能,我会将它放在控制器的文件中。您可以在类定义之外粘贴一个函数,它将像一个助手一样工作并且全局可用(只要加载了该控制器)。您还可以在视图内定义函数。很糟糕,但有可能。我不喜欢经常这样做,因为它不寻常且出乎意料(由我自己或其他开发人员)

于 2013-07-23T17:28:30.360 回答