Laravel中控制器实例化model的方法有什么不妥 请指点


我在每个控制器的初始化方法中实例化了相应的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);
        }
    }

}

laravel PHP框架 php

盖楼di一块砖 10 years, 2 months ago

如果是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直接用静态方法。

NeoJAY answered 10 years, 2 months ago

Your Answer