php - Laravel中控制器实例化model的方法有什么不妥 请指点
阿神
阿神 2017-04-10 15:18:09
[PHP讨论组]

我在每个控制器的初始化方法中实例化了相应的Model,然后在各个方法里使用,不知道这样有什么不妥,感觉自己实现的不够优雅。 主要是网站有很多模块,都是差不多的功能,部分代码是替换了model名称实例化。

public function __construct()
    {
        parent::__construct();
        $this->model = new \Line();
    }


public function store()
{
    $input = \Input::all();
    $validator = \Validator::make($input,$this->model->getRules('create'),$this->model->getMessage());
    if ($validator->fails())
    {
        return \Redirect::back()->with('errorCode',1)->withErrors($validator)->withInput();
    }else{
        if($model = $this->model->create($input)){
            return \Redirect::back()->with('errorCode',0);
        }else{
            return \Redirect::back()->with('errorCode',2);
        }
    }

}
阿神
阿神

闭关修行中......

全部回复(1)
迷茫

如果是Model的话,不需要这样做。

你是store可以这样写:

public function store()
{
    $input = \Input::all();
    $validator = \Validator::make($input, Line::getRules('create'), Line::getMessage());
    if ($validator->fails())
    {
        return \Redirect::back()->with('errorCode',1)->withErrors($validator)->withInput();
    }else{
        if($model = Line::create($input)){
            return \Redirect::back()->with('errorCode',0);
        }else{
            return \Redirect::back()->with('errorCode',2);
        }
    }

}

Lind的getRules和getMessage和具体的对象没有关系的话,就写成静态方法。
下面的create直接用静态方法。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号