如何进一步清理此控制器?

时间:2014-01-02 00:24:22

标签: php model controller laravel

我正在使用Laravel作为我的应用程序,我的注册表单路由到我的控制器中的postRegister()函数:

public function postRegister() {
    $validator = new Services\Validators\User;
    if ($validator->passes()) {
        $user = new User();
        $user->firstname = Input::get('firstname');
        $user->lastname = Input::get('lastname');
        $user->email = Input::get('email');
        $user->password = Hash::make(Input::get('password'));
        $user->birthday = Input::get('birthday');
        $user->save();
        return Redirect::to('login');
    }
    return Redirect::to('register')->withInput()->withErrors($validator->getErrors());
}

现在,我已经设法将验证移动到存储规则和消息的服务,但我还想将if ($validator->passes())块移动到某个地方,这是我能想到的唯一一个地方这样做是合适的用户模型。但是,我不能那样做,因为我已经在操纵那个类的实例了。

这是否干净有效,因为我可以 或是否有另一种方式?感谢。

2 个答案:

答案 0 :(得分:0)

查看https://github.com/laravelbook/ardent

这是一个扩展Eloquent的Laravel软件包。它几乎可以完全满足您的需求。

就个人而言,我认为你现在所处的位置并没有任何问题。但是Ardent会让你的控制器更加精益。

答案 1 :(得分:0)

您可以在Laravel文档中查看Mass Assignment。那么你可以拥有

警告:未经测试的代码......

public function postRegister() {
    $validator = new Services\Validators\User;
    if ($validator->passes()) {
        $user = new User(array (
          'firstname'=>Input::get('firstname'),
          'lastname'=>Input::get('lastname'),
          'email'=>Input::get('email'),
          'birthday'=>Input::get('birthday'),
          'password'=>Hash::make(Input::get('password'))
        ));
        $user->save();
        return Redirect::to('login');
    }
    return Redirect::to('register')->withInput()->withErrors($validator->getErrors());
}

额外奖金提示 - 我们可以在密码上使用mutator。那么User模型之外的任何人都不需要知道我们如何处理散列密码。

在用户模型中设置setPasswordAttribute功能后......

class User extends Eloquent {

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

}

...我们可以通过调用$user->password = Input::get('password');来设置密码,并在将值保存到模型之前对其进行哈希处理。