欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

laravel5創(chuàng)建service provider和facade的方法詳解

 更新時間:2016年07月26日 11:47:54   作者:軒脈刃  
這篇文章主要介紹了laravel5創(chuàng)建service provider和facade的方法,實例分析了laravel創(chuàng)建service、provider和facade類的具體步驟與實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了laravel5創(chuàng)建service provider和facade的方法。分享給大家供大家參考,具體如下:

laravel5創(chuàng)建一個facade,可以將某個service注冊個門面,這樣,使用的時候就不需要麻煩地use 了。文章用一個例子說明怎么創(chuàng)建service provider和 facade。

目標

我希望我創(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',
  ],
];

總結(jié)

laravel5中使用facade還是較為容易的,基本和4沒啥區(qū)別。

更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php日期與時間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論