[英]Where do I place a function which I would like to use in multiple controllers and not just in the controller in which I've created it?
[英]In Laravel project, where do I put code which reads data from database tables, which would be common to multiple controllers?
背景:
I am having my first encounter with any MVC framework, as I am developing a little application with PHP web framework Laravel v6 and MongoDB (with jenssegers moloquent) as database engine. 我正在按照本教程系列學習 Laravel 6。
通常,當我使用簡單的 php 開發此類應用程序時,我會創建一個名為readFromDb.php
的文件,並在其中從所有 DB 表(Mongodb 中的集合)中查找/讀取/選擇數據。 然后我將包含在每個 PHP 文件的頂部,我需要在其中對來自 DB 的任何數據進行一些處理。
例如,如果我有以下 collections
I would select all records/documents from them into associative arrays in the readFromDb.php
, and then include readFromDb.php
on top of every page where I would need to display or do processing on data from DB.
問題:
Now, in Laravel, should I create such a script called readFromDb.php
and include it on top of every function in every single controller? 在這種情況下,我應該將這個readFromDb.php
文件放在哪里,以及如何將它包含在控制器中?
或者我應該在使用數據庫中的數據之前編寫代碼以從每個 controller 中的每個 function 中的相關數據庫集合/表中讀取?
我正在使用 class 並將其稱為repository
以通過數據庫處理我的所有請求
首先我創建一個文件UserRepository
<?php
namespace App\Repositories;
use App\Model\User;
class UserRepository
{
function getUsers(){
Return User::get();
}
}
然后在contruct
中,只需要調用construct的parent中的repository
即可
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
protected $user;
function __construct(){
$this->user = new UserRepository();
}
function index(){
$users = $this->user->getUser(); // getUser() is the function inside the repository class
return view('user',compact('users'));
}
}
That's how I do code in laravel, because i dont want to call Laravel Model
and do all the store, reads inside Controller and cause messy code
Laravel有Eloquent ORM什么是Object關系映射接口。
簡介:
Laravel 隨附的 Eloquent ORM 提供了一個漂亮、簡單的ZECC2C67B8092666170273A452D6實現。 每個數據庫表都有一個相應的“模型”,用於與該表進行交互。 模型允許您查詢表中的數據,以及將新記錄插入表中。
基本上,與您的readFromDb.php
文件相同,但它使用 OOP 處理,因此代碼庫非常易於理解和擴展,並且與您的代碼嚴格相關。
使用 Eloquent 查詢時,您使用模型。 如果您的查詢結果有單行,您將獲得單個Model ,如果您的結果有多行,您將獲得Eloquent\Collection結果集包含您的模型。
最后,你不能在 Laravel 中寫 ORM 因為你已經有了。
如果您認為高級抽象訪問器; 你應該探索設計模式。 之后,您可以考慮存儲庫模式、裝飾器模式等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.