MVC 中控制器和模型的区别

发布于 2024-11-16 05:23:26 字数 461 浏览 2 评论 0原文

我对 MVC 框架(codeIgniter)中的控制器和模型有点困惑。我很清楚控制器方法调用视图,模型方法与数据库交互。 但是,我对以下类型的方法有点困惑,这些方法是由控制器中的方法调用的。

hash_password              //returns hash password. 
valid_email               //validates email format and return true or false
is_logged                //check if session has a variable, returns true or false
generate_random_string  //generates and hashes a random string

它们应该放置在控制器中还是模型中?

目前我将上述所有功能都放在一个控制器中。正确吗?

I'm little confused about controller and model in MVC framework (codeIgniter). Its clear to me that controller methods calls the views and Model methods interact with database.
However, I'm little confused about the following types of methods, which are called by methods in a controller.

hash_password              //returns hash password. 
valid_email               //validates email format and return true or false
is_logged                //check if session has a variable, returns true or false
generate_random_string  //generates and hashes a random string

Should they be placed in controller or in a model?

Currently I place all of the above functions in a controller. Is it correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

任谁 2024-11-23 05:23:26

我认为 is_logged 应该放置在 User 的模型中。请注意,User 可能是您案例中的客户,也可能是您为服务用户建模而创建的任何类。

valid_emailgenerate_random_string 或多或少是实用函数,您可以将它们放置在 UtilityUtilities 模型中,以便它们可以在您的应用程序的各种控制器中重复使用。

hash_password 可以放置在 User 模型或 Utility 模型中。我更倾向于将其放入 Utility 模型中,因为它是一个哈希函数,并且用户不关心任何内容。然而,我可以想象否则可能会有争论。

以下SO问题(尽管针对不同的框架)也可以作为经验法则:

Zend Framework 1.10 中自定义函数的放置位置

I think the is_logged should be placed in the Model for User. Note that the User might be a customer in your case or any class that you have made to model a user of your service.

The valid_email and generate_random_string are more or less utility functions, which you can place in a Utility or Utilities model, so that these are reusable in various controllers in your application.

The hash_password, can be placed in either the User model or Utility model. I am more tempted to place it in Utility model, since its a hashing function and there is nothing the user cares about. However, I can imagine there can be argument(s) otherwise.

The following SO question (though for a different framework) can also serve as a rule of thumb:

Where to put custom functions in Zend Framework 1.10

无语# 2024-11-23 05:23:26

通常控制器用于确定如何处理发出的http请求。

创建一些直接响应http请求的函数并没有什么错。

但如果它与数据库有关,最好将这些函数放在模型中,并从控制器调用它们。

generally controllers are used to determine how to handle the http requests made..

There's nothing wrong in creating some functions which directly respond to the http requests.

but if it has anything to do with the DB, its better to place those function in the model, and call them from the controller.

花开浅夏 2024-11-23 05:23:26

控制器应该将视图与模型结合起来,因此每个验证都应该放在模型中
这是我来自 kohana 的示例

CONTROLLER

<?php
/**
 * User Controller
 */
class Controller_Admin_User extends Controller_Admin_Template {

    public function action_index()
    {
        $this->template->body = View::factory('admin/user/index')
                ->set('i', 0)
                ->bind('users', $users)
                ->bind('groups', $groups)
                ->bind('id_user_group', $id_user_group);

        $model_user = new Model_Admin_User;
        $users = $model_user->get_users(Arr::get($_GET, 'sort'), Arr::get($_GET, 'order'));

        $model_usergroup = new Model_Admin_Usergroup;
        $groups = $model_usergroup->get_user_group();
    }

    public function action_add()
    {
        $this->template->body = View::factory('admin/user/form_add')
                ->bind('error', $error)
                ->bind('groups', $groups)
                ->bind('post', $post);

        $model_usergroup = new Model_Admin_Usergroup;
        $groups = $model_usergroup->get_user_group();

        if($_POST)
        {
            $model_user = new Model_Admin_User;
            if($model_user->save($_POST) == false)
            {
                $error = $model_user->error;
                $post = $_POST;
            }
            else
            {
                $this->request->redirect('admin/user');
            }
        }
    }

MODEL

class Model_Back_User extends Model {

    private $qb;

    public $aliases = array(
        'id'=> 'id_user'
    );

    public $error = array(
        'name'          => null,
        'surname'       => null,
        'login'         => null,
        'password'      => null,
        'id_user_group' => null,
        'old_password'  => null,
        'new_password'  => null,
        'confirm'       => null,
        'email'         => null,
        'phone'         => null,
    );

    private $rules = array(
        'name'          => array('not_empty' => null, 'alpha' => null),
        'surname'       => array('not_empty' => null, 'alpha' => null),
        'login'         => array('not_empty' => null),
        'password'      => array('not_empty' => null),
        'id_user_group' => array('not_empty' => null),
        'email'         => array('not_empty' => null, 'email' => null),
        'phone'         => array('not_empty' => null),
        'old_password'  => array('not_empty' => null),
        'new_password'  => array('not_empty' => null),
        'confirm'       => array('matches'   => array('new_password'))
    );

    public function __construct()
    {
        $this->qb = new Querybuilder;
        //parent::__construct();
    }

    public function change_password($data)
    {       
        $validate = Validate::factory($data)
            ->filter(true,              'trim')
            ->rules('old_password',     $this->rules['old_password'])
            ->rules('new_password',     $this->rules['new_password'])
            ->rules('confirm',          $this->rules['confirm'])
            ->callback('old_password',  array($this, 'password_exists'), array('id_user'=> $data['id_user']));

        if($validate->check() == false)
        {
            $this->error = array_merge($this->error, $validate->errors('user'));
            return false;
        }

        $u = Session::instance()->get('user');
        $this->edit(array('password'=> $this->password($data['new_password'])), array('id_user'=> $u['id_user']));
        return true;
    }

    public function password_exists(Validate $valid, $field, $param)
    {
        if($this->user_exists(array('password'=> $this->password($valid[$field]), 'id_user'=> $param['id_user'])) == false)
        {
            $valid->error($field, 'old password is incorrect', array($valid[$field]));
        }
    }

    public function save($data)
    {
        $validate = Validate::factory($data)
            ->filter(true, 'trim')
            ->rules('name', $this->rules['name'])
            ->rules('surname', $this->rules['surname'])
            ->rules('user_group_id', $this->rules['id_user_group'])
            ->rules('email', $this->rules['email'])
            ->rules('phone', $this->rules['phone']);

        $edit = false;
        if(isset($data['id_user']) AND Validate::not_empty($data['id_user']))
        {
            $edit = true;
        }
        else
        {
            $validate->rules('login', $this->rules['login'])
                    ->rules('password', $this->rules['password']);
        }

        if($validate->check() == false)
        {
            $this->error = array_merge($this->error, $validate->errors('user'));
            return false;
        }

        if($edit == true)
        {
            $this->edit(
                array(
                    'name'          => $data['name'],
                    'user_group_id' => $data['user_group_id']
                ),
                array(
                    'id_user'=> $data['id_user']
                )
            );
            return true;
        }
        return $this->add(
                    array(
                        'name'          => $data['name'],
                        'login'         => $data['login'],
                        'password'      => $data['password'],
                        'user_group_id' => $data['user_group_id']
                    )
                );
    }

    protected function add($data)
    {        
        $data['password'] = $this->password($data['password']);

        return $this->_db->query(Database::INSERT, 
            $this->qb->insert('user')->set($data)->build_query()
        );
    }

View 并不那么重要,这就是为什么我不把它放在这里。

Controller should combine view with model, so every validation shoulde be placed in model
this is my example from kohana

CONTROLLER

<?php
/**
 * User Controller
 */
class Controller_Admin_User extends Controller_Admin_Template {

    public function action_index()
    {
        $this->template->body = View::factory('admin/user/index')
                ->set('i', 0)
                ->bind('users', $users)
                ->bind('groups', $groups)
                ->bind('id_user_group', $id_user_group);

        $model_user = new Model_Admin_User;
        $users = $model_user->get_users(Arr::get($_GET, 'sort'), Arr::get($_GET, 'order'));

        $model_usergroup = new Model_Admin_Usergroup;
        $groups = $model_usergroup->get_user_group();
    }

    public function action_add()
    {
        $this->template->body = View::factory('admin/user/form_add')
                ->bind('error', $error)
                ->bind('groups', $groups)
                ->bind('post', $post);

        $model_usergroup = new Model_Admin_Usergroup;
        $groups = $model_usergroup->get_user_group();

        if($_POST)
        {
            $model_user = new Model_Admin_User;
            if($model_user->save($_POST) == false)
            {
                $error = $model_user->error;
                $post = $_POST;
            }
            else
            {
                $this->request->redirect('admin/user');
            }
        }
    }

MODEL

class Model_Back_User extends Model {

    private $qb;

    public $aliases = array(
        'id'=> 'id_user'
    );

    public $error = array(
        'name'          => null,
        'surname'       => null,
        'login'         => null,
        'password'      => null,
        'id_user_group' => null,
        'old_password'  => null,
        'new_password'  => null,
        'confirm'       => null,
        'email'         => null,
        'phone'         => null,
    );

    private $rules = array(
        'name'          => array('not_empty' => null, 'alpha' => null),
        'surname'       => array('not_empty' => null, 'alpha' => null),
        'login'         => array('not_empty' => null),
        'password'      => array('not_empty' => null),
        'id_user_group' => array('not_empty' => null),
        'email'         => array('not_empty' => null, 'email' => null),
        'phone'         => array('not_empty' => null),
        'old_password'  => array('not_empty' => null),
        'new_password'  => array('not_empty' => null),
        'confirm'       => array('matches'   => array('new_password'))
    );

    public function __construct()
    {
        $this->qb = new Querybuilder;
        //parent::__construct();
    }

    public function change_password($data)
    {       
        $validate = Validate::factory($data)
            ->filter(true,              'trim')
            ->rules('old_password',     $this->rules['old_password'])
            ->rules('new_password',     $this->rules['new_password'])
            ->rules('confirm',          $this->rules['confirm'])
            ->callback('old_password',  array($this, 'password_exists'), array('id_user'=> $data['id_user']));

        if($validate->check() == false)
        {
            $this->error = array_merge($this->error, $validate->errors('user'));
            return false;
        }

        $u = Session::instance()->get('user');
        $this->edit(array('password'=> $this->password($data['new_password'])), array('id_user'=> $u['id_user']));
        return true;
    }

    public function password_exists(Validate $valid, $field, $param)
    {
        if($this->user_exists(array('password'=> $this->password($valid[$field]), 'id_user'=> $param['id_user'])) == false)
        {
            $valid->error($field, 'old password is incorrect', array($valid[$field]));
        }
    }

    public function save($data)
    {
        $validate = Validate::factory($data)
            ->filter(true, 'trim')
            ->rules('name', $this->rules['name'])
            ->rules('surname', $this->rules['surname'])
            ->rules('user_group_id', $this->rules['id_user_group'])
            ->rules('email', $this->rules['email'])
            ->rules('phone', $this->rules['phone']);

        $edit = false;
        if(isset($data['id_user']) AND Validate::not_empty($data['id_user']))
        {
            $edit = true;
        }
        else
        {
            $validate->rules('login', $this->rules['login'])
                    ->rules('password', $this->rules['password']);
        }

        if($validate->check() == false)
        {
            $this->error = array_merge($this->error, $validate->errors('user'));
            return false;
        }

        if($edit == true)
        {
            $this->edit(
                array(
                    'name'          => $data['name'],
                    'user_group_id' => $data['user_group_id']
                ),
                array(
                    'id_user'=> $data['id_user']
                )
            );
            return true;
        }
        return $this->add(
                    array(
                        'name'          => $data['name'],
                        'login'         => $data['login'],
                        'password'      => $data['password'],
                        'user_group_id' => $data['user_group_id']
                    )
                );
    }

    protected function add($data)
    {        
        $data['password'] = $this->password($data['password']);

        return $this->_db->query(Database::INSERT, 
            $this->qb->insert('user')->set($data)->build_query()
        );
    }

View is not so important thats why i dont put this here.

枫以 2024-11-23 05:23:26

一般来说 - 模型应该了解它自己的数据。因此,任何纯粹与模型自身数据相关的内容都应该放入模型中。

例如, hash_password 和电子邮件验证方法 - 模型应该知道如何验证或更新它自己的数据字段,因此这些应该放入模型中。

然而,控制器应该知道如何正确地引导用户操作并为视图等加载正确的模型。

例如,与会话相关的方法应该放在控制器中,因为会话用于存储用户的状态(基于过去的操作) 。

“生成随机字符串”方法非常模糊,可能到处都在使用。我会将其放在一个单独的库中,可能酌情包含在模型/控制器中。

Generally speaking - a model should know stuff about it's own data. So anything related purely to a model's own data - should go in the model.

Eg the hash_password and email-validation methods - a model should know how to validate or update it's own data-fields, so those should go in the model.

However a controller should know about how to direct user actions appropriately and to load the correct models for views etc.

EG the session-related method should go in the controller, because the session is used for storing the user's state (based on past actions).

The "generate random string" method is very vague and may be used everywhere. I'd put that in a separate library possibly included in the model/controller as appropriate.

平安喜乐 2024-11-23 05:23:26

我已经使用 Codeigniter 很长时间了,就放置而言,我会使用您的函数执行以下操作:

hash_password              //returns hash password. 

我将密码哈希器之类的东西放在库或帮助程序文件中,这样我就可以从我的控制器中调用它,例如:

// pretend library I'd make for tasks like hashing etc
$this->load->library('passwords');
// transform posted password into it's hashed version   
$password = $this->password_library->hash_password($this->input->post('password'));

我假设您想对密码进行哈希/盐处理并将其存储在该示例中的数据库中

valid_email               //validates email format and return true or false

这已经在 form_validation 中,所以...

is_logged                //check if session has a variable, returns true or false

这也应该连接到身份验证库

generate_random_string  //generates and hashes a random string

同样,这将来自库或助手。

那么什么时候使用模型呢?

我,我专门使用模型进行数据库的输入/输出。我所有的疑问都在那里。我通常让模型的函数返回数据对象,这样我就可以在视图中循环遍历它们。

控制器从模型中调用数据,然后将所有内容转储到视图中。外部功能总是进入库和助手中。我喜欢做“MY_library”并扩展 Codeigniter 自己的东西 - 特别是表单和 html 帮助器等。

I've been using Codeigniter for a long time and I'd do the following with your functions as far as placement goes:

hash_password              //returns hash password. 

I'd put something like a password hasher in a library or helper file so I could call it from my controller like:

// pretend library I'd make for tasks like hashing etc
$this->load->library('passwords');
// transform posted password into it's hashed version   
$password = $this->password_library->hash_password($this->input->post('password'));

I'm assuming you want to hash/salt the password and store it in your database in that example

valid_email               //validates email format and return true or false

This is already in form_validation, so...

is_logged                //check if session has a variable, returns true or false

This should also connect to a authentication library

generate_random_string  //generates and hashes a random string

Again, this would come from a library or helper.

SO WHEN DO YOU USE A MODEL?

Me, I use models exclusively for in/out on the database. All my queries go in there. I usually have my model's functions return data objects so I can loop through them in my views.

Controllers call your data from your models, then dump everything into your views. Outside functionality always goes into libraries and helpers. I like to do the "MY_library" and extend Codeigniter's own stuff - especially with forms and the html helper etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文