在一些中大型的應(yīng)用架構(gòu)設(shè)計中,通常會把模型分成數(shù)據(jù)層、邏輯層和服務(wù)層,控制器只會調(diào)用服務(wù)層方法。而查詢邏輯則基本上被封裝到邏輯層里面,數(shù)據(jù)層僅僅是做模型的各種定義。
而在簡單的應(yīng)用里面,也可以采用PHP的Trait機制來實現(xiàn)代碼的復(fù)用機制。
用查詢范圍或搜索器簡化查詢
如果你使用模型查詢的話,把你的查詢條件盡量封裝到查詢范圍或者搜索器方法里面,查詢范圍和搜索器的區(qū)別主要在于查詢范圍比較適合定義一組(多個字段)查詢條件,如果要調(diào)用多個查詢范圍需要多次調(diào)用,而搜索器比較適合定義一個字段(其實并非絕對)的查詢條件,只需要調(diào)用一次withSearch方法。
使用查詢范圍和搜索器的例子。
<?php namespace appindexmodel; use thinkModel; class User extends Model { public function scopeVip($query) { $query->where('user_type', 'vip') ->where('status', 1) ->field('id,name'); } public function searchAgeAttr($query, $age) { $query->where('age','>',$age); } public function searchScoreAttr($query, $score) { $query->where('score','<=',$score)->where('score', '>' ,0); } }
控制器代碼
<?php namespace appindexcontroller; use thinkController; use thinkRequest; class index extends Controller { public function index(Request $request) { // 查詢VIP會員 User::vip()->select(); // 查詢年齡和分?jǐn)?shù) User::withSearch(['age,'score''], $request->param())->select(); } }
在控制器代碼中,我們只關(guān)注業(yè)務(wù)邏輯本身,而不需要關(guān)注這個邏輯內(nèi)部的查詢條件是什么。更詳細(xì)的關(guān)于搜索器和查詢范圍的內(nèi)容可以參考官方手冊。
PHP中文網(wǎng),有大量免費的ThinkPHP入門教程,歡迎大家學(xué)習(xí)!
本文轉(zhuǎn)自:https://blog.thinkphp.cn/833794
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com