0
public function store()
{
  $input = Input::all();
  $validator = User::validate($input);

  if(!$validator->passes()) {
    $notification['danger'] = 'There were validation errors!';
    return Redirect::route('user.create')->withInput()->withErrors($validator)->with('notification', $notification);
  }

  $input['password'] = Hash::make($input['password']);
  $user = $this->user->create($input);
  $role = $this->role->find($input['role_id']);
  $user->roles()->save($role);

  $notification['success'] = "User $user->email sucessfuly created.";
  return Redirect::route('user.index')->with('notification', $notification);    
}

だから私はアーキテクチャについてたくさん読んできましたが、これが「良い」方法ではないことはわかっていますが、解決策はあまり思いつきません。

これを UserRepository UserFormValidator などの一連のクラスに抽出することは、オーバーエンジニアリングのように聞こえます。特に私の場合、それはかなり小さなプロジェクトであり、数週間しか続かないでしょう。

私がもっと興味を持っているのは、このビジネス ロジックを User モデルに抽出する方法です。関係を介して他のモデルを関連付けることは、私の意見では、とにかくモデルの問題です。私の現在のモデル コードは、hasMany()、begsTo() などの関係と、$filleable、$hidden プロパティのみを設定します。

とにかく、私は提案を受け入れています。

4

2 に答える 2

0

これは小さなプロジェクトであり、コードを User モデルに移動することを考えているため、リファクタリングできるコードのチャンクを次に示します。

それ以外の:

  $role = $this->role->find($input['role_id']);
  $user->roles()->save($role);

書く:

       $role = $this->role->find($input['role_id']);
       $user->addRole($role);

そしてあなたの User モデルで:

class User extends Eloquent
{
   public function addRole($role)
   {
          if(!is_null($role) and is_object($role) and $role->id > 0)
          {
              return    $this->roles()->save($role);
          }
          else
          {
               throw new RoleNotFoundException($role);
          }
   }
}

次に、global.php ファイルで、このタイプの例外のエラー ハンドラーを定義します。

App::error(function(RoleNotFoundException $exception)
{
    // Handle the exception...
    return Response::make('Error! ' . $exception->getCode());
});

これにより、コードがより読みやすく、より堅牢になり、メソッドを実装するときに Laravel の詳細を覚える必要がなくなります。これが、メソッドを User モデルでラップする理由です。この例ではかなり単純ですが、このアプローチにより、より複雑なシナリオで多くの頭痛の種を取り除くことができます。

于 2013-10-19T10:11:53.400 に答える