今天就跟大家聊聊有關(guān)laravel5中怎么創(chuàng)建service,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

目標
我希望我創(chuàng)建一個AjaxResponse的facade,這樣能直接在controller中這樣使用:
class MechanicController extends Controller {
public function getIndex()
{
\AjaxResponse::success();
}
}它的作用就是規(guī)范返回的格式為
{
code: "0"
result: {
}
}步驟
創(chuàng)建Service類
在app/Services文件夾中創(chuàng)建類
<?php namespace App\Services;
class AjaxResponse {
protected function ajaxResponse($code, $message, $data = null)
{
$out = [
'code' => $code,
'message' => $message,
];
if ($data !== null) {
$out['result'] = $data;
}
return response()->json($out);
}
public function success($data = null)
{
$code = ResultCode::Success;
return $this->ajaxResponse(0, '', $data);
}
public function fail($message, $extra = [])
{
return $this->ajaxResponse(1, $message, $extra);
}
}這個AjaxResponse是具體的實現(xiàn)類,下面我們要為這個類做一個provider
創(chuàng)建provider
在app/Providers文件夾中創(chuàng)建類
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AjaxResponseServiceProvider extends ServiceProvider {
public function register()
{
$this->app->singleton('AjaxResponseService', function () {
return new \App\Services\AjaxResponse();
});
}
}這里我們在register的時候定義了這個Service名字為AjaxResponseService
下面我們再定義一個門臉facade
創(chuàng)建facade
在app/Facades文件夾中創(chuàng)建類
<?php namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class AjaxResponseFacade extends Facade {
protected static function getFacadeAccessor() { return 'AjaxResponseService'; }
}修改配置文件
好了,下面我們只需要到app.php中掛載上這兩個東東就可以了
<?php return [ ... 'providers' => [ ... 'App\Providers\RouteServiceProvider', 'App\Providers\AjaxResponseServiceProvider', ], 'aliases' => [ ... 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AjaxResponse' => 'App\Facades\AjaxResponseFacade', ], ];
看完上述內(nèi)容,你們對laravel5中怎么創(chuàng)建service有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
本文題目:laravel5中怎么創(chuàng)建service-創(chuàng)新互聯(lián)
分享鏈接:http://chinadenli.net/article46/dhcgeg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務、微信公眾號、建站公司、商城網(wǎng)站、企業(yè)建站、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容