Laravel 5.2 了解 "fat model, skinny controller"

Laravel 5.2 understanding "fat model, skinny controller"

我正在尝试了解如何在 Laravel 5.2 中使用 "fat model, skinny controller"。基本上,我主要理解为什么,是什么,但不知道怎么做。我已经在谷歌上搜索了一段时间,我找到了几页描述为什么(有些页面描述了为什么不)和什么,但是没有页面可以很容易地理解如何使用瘦控制器创建胖模型。

我创建了一个非常基本的待办事项列表,无需登录或验证,只有最基本的待办事项记录功能。该应用程序基本上使用 "skinny model, fat controllers",我想重写该应用程序,以便它使用 "fat model, skinny controllers"。

我在 MySQL-数据库中有三个 table:

当我为 table 创建迁移时,我使用了 $table->foreign('user_id')->references('id')->on('users');$table->foreign('project_id')->references('id')->on('projects'); 用于注释 table 迁移。由于某种原因它不起作用,所以在数据库中 notes.user_idnotes.project_id 不是 users.idprojects.id 的外键,这是一开始的想法。我猜这对我下面的问题来说并不重要,但如果确实如此,请有人告诉我,这样我就可以尝试解决这个问题。

我有以下模型(已删除文档块)

app\User.php:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function notes()
    {
        return $this->hasMany(Note::class);
    }
}

app\Project.php:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    public function notes()
    {
        return $this->hasMany(Note::class);
    }
}

app\Note.php:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}

我有以下控制器(已删除文档块)

app\Http\Controllers\UserController.php:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Response;

class UserController extends Controller
{
    public function index()
    {
        try {
            $statusCode = 200;
            $users = User::orderBy('uname', 'asc')->get()->toArray();
            $response = [];

            foreach ($users as $user) {
                $this_row = array(
                    'id' => $user['id'],
                    'name' => $user['uname'],
                );

                $response[] = $this_row;
            }
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return Response::json($response, $statusCode);
        }
    }
}

app\Http\Controllers\ProjectController.php:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Project;
use Response;

class ProjectController extends Controller
{
    public function index()
    {
        try {
            $statusCode = 200;
            $projects = Project::orderBy('pname', 'asc')->get()->toArray();
            $response = [];

            foreach ($projects as $project) {
                $this_row = array(
                    'id' => $project['id'],
                    'name' => $project['pname'],
                );

                $response[] = $this_row;
            }
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return Response::json($response, $statusCode);
        }
    }
}

app\Http\Controllers\NoteController.php:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Note;
use App\User;
use App\Project;
use Input;
use Response;
use Redirect;

class NoteController extends Controller
{
    public function index()
    {
        try {
            $statusCode = 200;
            $notes = Note::where('removed', 0)
                ->orderBy('time_created', 'asc')->get()->toArray();
            $response = [];

            foreach ($notes as $note) {
                $user = User::find($note['user_id']); // Username for note
                $project = Project::find($note['project_id']); // Project name

                $this_row = array(
                    'id' => $note['id'],
                    'user' => $user['uname'],
                    'project' => $project['pname'],
                    'content' => $note['content'],
                    'completed' => $note['completed'],
                    'created' => $note['time_created'],
                    'deadline' => $note['time_deadline']
                );

                $response[] = $this_row;
            }
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return Response::json($response, $statusCode);
        }
    }

    public function destroy(Request $request)
    {
        try {
            $statusCode = 200;

            $note = Note::find($request->id);
            $note->removed = 1;
            $note->save();
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return $statusCode;
        }        
    }

    public function edit($request) 
    {
        try {
            $statusCode = 200;

            $note = Note::find($request);

            $response = array(
                'id' => $note['id'],
                'content' => $note['content'],
                'completed' => $note['completed'],
                'deadline' => $note['time_deadline']
            );
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return Response::json($response, $statusCode);
        }
    }

    public function update(Request $request)
    {
        try {
            $statusCode = 200;

            $note = Note::find($request->id);

            $note->content = $request->content;
            $note->time_deadline = $request->deadline;

            if ($request->completed == "true") {
                $note->completed = 1;
            } else {
                $note->completed = 0;
            }

            $note->save();
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return $statusCode;
        }
    }

    public function store(Request $request)
    {
        try {
            $statusCode = 200;

            $note = new Note;

            $note->user_id = $request->user;
            $note->project_id = $request->project;
            $note->content = $request->content;
            $note->time_deadline = $request->deadline;

            $note->save();
        } catch (Exception $e) {
            $statusCode = 400;
        } finally {
            return $statusCode;
        }    
    }
}

最后,这是我的 app/Http/routes.php(评论已删除)

<?php

Route::get('/', function () {
    return view('index');
});

Route::get('/notes', 'NoteController@index');
Route::get('/notes/{id}', 'NoteController@edit');
Route::delete('/notes', 'NoteController@destroy');
Route::put('/notes', 'NoteController@store');
Route::post('/notes', 'NoteController@update');

Route::get('/projects', 'ProjectController@index');
Route::get('/users', 'UserController@index');

Route::group(['middleware' => ['web']], function () {
    //
});

完整的代码可以在我的 GitHub here.

找到

我正在使用 Angular 接收控制器发送的 JSON。这适用于我当前的页面,但如您所见,我的控制器有很多逻辑,我想将其移至模型。我不明白我是怎么做到的,所以这是我的问题:

你的瘦控制器可能是下面的,它会做同样的事情:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Project;

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::orderBy('pname', 'asc')->get(['id', 'name']);
        return response()->make($projects);
    }
}

但是正如 Fabio 提到的,如果您想更进一步,请查看存储库。这是一篇好文章:https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/

在大多数情况下,我将存储库包装到服务中以创建业务逻辑。 Controllers 只处理路由,models 只包含关系或修改器和访问器。但它可能因开发方法而异。

此外,不要在 foreach 循环中进行数据库查询,利用 Eloquent 的优势,例如:

$notes = Note::where('removed', 0)
            ->with(['user', 'project'])
            ->orderBy('time_created', 'asc')->get();

你可以这样访问:

foreach($notes as $note)
{
    echo $note->user->uname;
}