2017-07-15 23 views
2

我目前是laravel的新手,我試圖用laravel來代替我的頭。學習laravel的原因是增加了我創建良好代碼的知識,並創建了一個易於管理的應用程序。出於這個原因,我將我的應用程序建立在一個可接受的標準上對我來說很重要。在laravel中查找數據庫邏輯的位置?

我已經閱讀了幾篇文章,但仍然不確定在哪裏組織事情。

截至目前,我的應用程序結構看起來像這樣:

app/ 
    Console 
    Exceptions 
    Http 
     Controllers 
      Auth 
      Message 
      Settings 
     Middleware 
    Providers 
    Traits 
     Message 
     Settings 

我的一個控制器看起來是這樣的:

<?php 

namespace App\Http\Controllers\Message; 

use DB; 
use Auth; 
use Request; 
use App\Http\Controllers\Controller; 

class TypeController extends Controller 
{ 
    public function __construct() { 
     $this->middleware('auth'); 
     $this->middleware('access'); 
    } 

    public function type() { 
     $this->adjustTypingStatus(1); 
    } 

    public function untype() { 
     $this->adjustTypingStatus(0); 
    } 

    protected function adjustTypingStatus ($level) { 
     DB::table('user_lobby_info') 
      ->where('userid', Auth::User()->id) 
      ->where('lobby', Request::get('lobbyid')) 
      ->update([ 'typing' => $level ]); 
    } 
} 

?> 

問題

什麼是更好的方法來將控制器分成更小,更易於管理的部分?我應該將數據庫邏輯放入模型中並調用模型的方法嗎?

+0

我注意到你的控制器方法是你引用數據庫類而不是模型。你能分享你的模型嗎? – Dom

+0

@DomDaFonte我沒有大部分模型設置。我想這是laravel的一部分,我不認爲是有用的,因爲我使用查詢生成器而不是引用現在更有意義的模型。 – Shawn31313

+0

好吧,我相信我現在明白了這個問題,我會回答一個答案,以澄清如何使用Laravel創建簡單的CRUD MVC應用程序。 – Dom

回答

1

這是我如何分解控制器邏輯和使用模型的中小型項目。

1.創建表和模型

該命令將創建模型和--migration會創建一個引用,你可以用它來創建模型的表中的藍圖類遷移文件。

php artisan make:model UserLobbyInfo --migration 

你似乎已經創建了一個數據庫,所以你可能要刪除的--migration,除非你想用它來創建一個使用藍圖架構。我個人喜歡使用遷移。你的模型將直接在應用程序文件夾下的Laravel 5

2.創建修改模型文件

你會發現在App文件夾中的模型文件。在你的模型中,如果你的模型不遵循Laravel約定,你應該添加你要插入或更新的字段(可批量填充的項目)和你的表的名字(Laravel假定駱駝的外殼表示不同的單詞,並且你的表格以一個's',所以它認爲你的表將是user_lobby_infos,在你的情況下,你的表名是user_lobby_info)。這是我如何根據你的數據在你上面的查詢更新:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class UserLobbyInfo extends Model 
{ 
// Define mass fillable items 
    protected $fillable = array('userid','lobby','typing'); 

//Define table 
    protected $table = 'user_lobby_info'; 

} 

你如何使用你的模型

這種模式現在已經從它的擴展照亮提供給它的所有方法\數據庫\雄辯\ Model類,所以你可以做以下的多:

//To query all content: 
$index = UserLobbyInfo::all(); 

//To query specific content: 
$userLobby = UserLobbyInfo::where('id', '=', 1)->first(); 

//Save things: 
$userLobbyInfo = UserLobbyInfo::where('id', '=', 1)->first(); 
$userLobbyInfo->lobby = Request::get('lobbyid') 
$userLobbyInfo->save(); 

//Using the model for your query above this is how you can send an update: 
UserLobbyInfo::where('userid', '=', Auth::User()->id) 
     ->where('lobby', '=', Request::get('lobbyid')) 
     ->update([ 'typing' => $level ]); 

3.創建控制器與CRUD相關的方法預罐頭這個命令將創建一個所有你通常在一個CRUD應用程序使用的方法(指數顯示,創建,保存,編輯,更新,刪除)

php artisan make:controller UserLobbyController --resource 

在每一個你想這些功能的控制器用您需要的方法添加相應的模型。

4.添加一個CRUD應用傳統上使用,並鏈接到--resource方法 如果使用--resource,你將能夠使用資源的功能,將你提供的所有的所有路由這些資源所需的路線。

Route::resource('userlobby', 'UserLobbyController'); 

,在你的路由文件將創建下列路線的CRUD應用程序運行典型的「PHP工匠路線:列表| grep的userlobby」一線你會看到這些路線:

|  | GET|HEAD | userlobby        | userlobby.index  | App\Http\Controllers\[email protected]       | web    | 
|  | POST  | userlobby        | userlobby.store  | App\Http\Controllers\[email protected]       | web    | 
|  | GET|HEAD | userlobby/create       | userlobby.create  | App\Http\Controllers\[email protected]       | web    | 
|  | GET|HEAD | userlobby/{userlobby}     | userlobby.show  | App\Http\Controllers\[email protected]       | web    | 
|  | PUT|PATCH | userlobby/{userlobby}     | userlobby.update  | App\Http\Controllers\[email protected]       | web    | 
|  | DELETE | userlobby/{userlobby}     | userlobby.destroy | App\Http\Controllers\[email protected]      | web    | 
|  | GET|HEAD | userlobby/{userlobby}/edit    | userlobby.edit  | App\Http\Controllers\[email protected]       | web    | 

5 。將你的控制器壓縮到CRUD方法 我只是在下面編輯和更新方法,因爲這會變得很長。但願這給你如何擊穿控制器上的一個想法:

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\UserLobbyInfo; // Add this to access your new model 
use App\Http\Requests; 

class UserLobbyController extends Controller 
{ 

    /** 
    * Show the form for editing the specified resource. 
    * 
    * @param int $id 
    * @return \Illuminate\Http\Response 
    */ 
    public function edit($id) 
    { 
     $updateLobby = UserLobbyInfo::where('id', '=', $id)->first(); //This queries the table specifically for the id, just for demo purposes. 

     return view('lobbies.edit', compact('updateLobby')); //This will send the above defined array to your view to pre-populate. 
    } 

    /** 
    * Update the specified resource in storage. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param int $id 
    * @return \Illuminate\Http\Response 
    */ 
    public function update(Request $request, $id) 
    { 
     $userLobby = UserLobbyInfo::where('userid', '=', Auth::User()->id) 
      ->where('lobby', '=', $request->lobbyid)->first(); 

     //Grab the UserLobby row you want to update. 
     $updateLobby->typing = $level; //update the typing value 
     $updateLobby->save(); // save it. 
    } 

對於更復雜的應用程序,我通常較重控制器邏輯遷移出來的一類,並使用它引用控制器類。在編寫具有多個表連接的複雜查詢時(特別是在該連接中需要多個where子句的連接)時,我也只使用DB :: class。

希望這有助於強調如何在Laravel中正確使用模型。

大量的這些信息可以在laravel文檔中找到。我也喜歡這張備忘單:laravel cheat sheet

還有其他問題,或者如果我沒有完全回答你的問題,請告訴我。

+0

因此可以將邏輯和查詢留在控制器中嗎?因爲我有混合想法 – Shawn31313

+0

在某個階段,你將不得不將邏輯傳遞到你的控制器。我通常嘗試在控制器中保留少於10行代碼的方法。如果你只是更新表中的一行,並有一個簡單的方法來查詢這些數據,那麼我會將它保存在控制器中。如果您需要從多行中檢索數據所需的複雜邏輯,或者您將在視圖中使用大型多表查詢,那麼我建議將它移出它自己的類,然後在控制器中使用該類。如果您要在多個控制器上重複使用某個功能,則尤其如此。 – Dom

+0

明白了。那麼操縱結果呢?例如,在我的一個控制器中,我拉取數據,然後在其上運行一些條件並修改數據。 – Shawn31313

1

使用Eloquent而不是原始SQL查詢或查詢生成器查詢。將所有與數據相關的邏輯放入Model類中:

public function getApprovedUsersWithPosts() 
{ 
    return $this->where('approved', true)->with('posts')->get(); 
} 

您的控制器應該非常小。切勿將查詢或其他邏輯放入控制器中。另外,使用DI代替正面:

protected $user; 

public function __construct(User $user) 
{ 
    $this->user = $user; 
} 

public function index() 
{ 
    return view('users.approved', [ 
     'users' => $this->user->getApprovedUsers() 
    ]); 
} 
+0

因此,模型應該嚴格關注從數據庫獲取數據而不是操縱數據?我會假設的操縱是控制器在那裏做的。 – Shawn31313