簡體   English   中英

如何在laravel中找到數據庫邏輯?

[英]Where to locate database logic in 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 ]);
    }
}

?>

問題

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

這就是我如何分解控制器邏輯並將模型用於中小型項目。

1.創建表格和模型

此命令將創建模型, - 遷移將創建一個遷移文件,該文件引用可用於創建模型表的BluePrint類。

php artisan make:model UserLobbyInfo --migration

您似乎已經創建了一個數據庫,因此您可能希望刪除--migration,除非您想使用它來使用BluePrint創建模式。 我個人喜歡使用遷移。 您的模型將直接在Laravel 5中的App文件夾下創建。

2.修改模型文件

您可以在App文件夾中找到您的Model文件。 在您的模型中,您應該添加您要插入或更新的字段(可填充的大量項目)和表格的名稱(如果它不符合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';

}

如何使用您的模型

此模型現在具有從其擴展的Illuminate \\ Database \\ Eloquent \\ 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相關方法創建預先控制的Controller此命令將創建一個控制器,其中包含您通常在CRUD應用程序中使用的所有方法(索引,顯示,創建,保存,編輯,更新,刪除)

php artisan make:controller UserLobbyController --resource

在每個功能中,您都可以使用所需的方法添加相應的模型。

4.添加傳統上在CRUD應用程序中使用的所有路由並鏈接到--resource方法如果使用--resource,您將能夠使用資源函數,該函數將為您提供這些相應資源所需的所有路徑。

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

您的路徑文件中的一行將在CRUD應用程序運行“php artisan route:list | grep userlobby”中創建以下路由,您將看到以下路由:

|        | GET|HEAD  | userlobby                                | userlobby.index      | App\Http\Controllers\UserLobbyController@index                          | web                |
|        | POST      | userlobby                                | userlobby.store      | App\Http\Controllers\UserLobbyController@store                          | web                |
|        | GET|HEAD  | userlobby/create                         | userlobby.create     | App\Http\Controllers\UserLobbyController@create                         | web                |
|        | GET|HEAD  | userlobby/{userlobby}                    | userlobby.show       | App\Http\Controllers\UserLobbyController@show                           | web                |
|        | PUT|PATCH | userlobby/{userlobby}                    | userlobby.update     | App\Http\Controllers\UserLobbyController@update                         | web                |
|        | DELETE    | userlobby/{userlobby}                    | userlobby.destroy    | App\Http\Controllers\UserLobbyController@destroy                        | web                |
|        | GET|HEAD  | userlobby/{userlobby}/edit               | userlobby.edit       | App\Http\Controllers\UserLobbyController@edit                           | 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.
    }

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

希望這有助於突出顯示如何在Laravel中正確使用模型。

laravel文檔中提供了大量此類信息。 我也喜歡這個備忘單: laravel備忘單

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

使用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()
    ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM