1. 首先定义ServiceContainer ,也就是实现业务逻辑的接口,例子为payment.php

 1 <?php
 2 
 3 namespace App\Payment;
 4 
 5 
 6 class Payment
 7 {
 8     
 9     public function add($a, $b)
10     {
11         return $a + $b;
12     }
13 }

2. 定义一个ServiceProvider供其他地方使用,也就是服务提供者。例子为PaymentServiceProvider.php

<?php

namespace App\Payment;

use Illuminate\Support\ServiceProvider;

class PaymentServiceProvider extends ServiceProvider
{
    /**
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('Payment', function () {
                return new Payment();
            }
        );
    }

    /**
     * @return array
     */
    public function provides()
    {
        return array('Payment');
    }
}

3. 在app/config.php中的providers数组中加入ServiceProvider,让系统自动注册

1 'providers' => [
2 
3     //其他服务提供者
4 
5     App\Payment\PaymentServiceProvider::class,
6 ],

4. 调用方法
第一种方法:

 1 <?php
 2 
 3 namespace App\Http\Controllers;
 4 
 5 use Illuminate\Support\Facades\App;
 6 
 7 class PaymentController extends Controller
 8 {
 9 
10     public function test()
11     {
12         $res = App::make("Payment");
13         echo $res->add(1, 2);
14       
15     }
16 }

这样太麻烦,还需要用make来获取对象,为了简便,就可以使用门面功能
第二种方法:
定义门面pay

 1 <?php
 2 namespace App\Payment\Facades;
 3 
 4 use Illuminate\Support\Facades\Facade;
 5 
 6 /**
 7  * Created by PhpStorm.
 8  * User: Yuki
 9  * Date: 2017/11/29
10  * Time: 11:30
11  */
12 class Pay extends Facade
13 {
14     /**
15      * @return string
16      */
17     protected static function getFacadeAccessor()
18     {
19         return 'Payment';
20     }
21 }

在控制器里就可以直接调用了

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: Yuki
 5  * Date: 2017/11/29
 6  * Time: 15:09
 7  */
 8 
 9 namespace App\Http\Controllers;
10 
11 use App\Payment\Facades\Pay;
12 use Illuminate\Support\Facades\App;
13 
14 class PaymentController extends Controller
15 {
16 
17     public function test()
18     {
19        //$res = App::make("payment");
20        //echo $res->add(1, 2);
21        echo  Pay::add(1, 2);
22 
23     }
24 }

 

posted on 2017-12-13 18:14  彼岸无花  阅读(196)  评论(0)    收藏  举报