标签:
namespace App\Helper; class MyFoo { public function add($a, $b) { return $a+$b; } }
<?php namespace App\Providers; use App\Helper\MyFoo; //要服务的Container use Illuminate\Support\ServiceProvider; use App; class MyFooServiceProvider extends ServiceProvider { public function boot(){} //注册到容器中 public function register() { //可以这么绑定,这需要use App; App::bind("myfoo",function(){ return new MyFoo(); }); //也可以这么绑定 $this->app->bind("myfoo", function(){ return new MyFoo(); }); } }
App\Providers\MyFooServiceProvider::class,
public function two($id=null) { //从系统容器中获取实例化对象 $myfoo = App::make("myfoo"); echo $myfoo->add(1,2); }
namespace App\Facades; use Illuminate\Support\Facades\Facade; class MyFooFacade extends Facade { protected static function getFacadeAccessor() { //这里返回的是ServiceProvider中注册时,定义的字符串 return ‘myfoo‘; } }
use App\Facades\MyFooFacade; public function two($id=null) { //从系统容器中获取实例化对象 $myfoo = App::make("myfoo"); echo $myfoo->add(1,2); //使用门面 echo MyFooFacade::add(4,5); }
总的来说,自定义了一个类,为了方便在其他别处使用,便可以使用服务提供者和门面
laravel中的Contracts, ServiceContainer, ServiceProvider, Facades关系
标签:
原文地址:http://www.cnblogs.com/hanyouchun/p/5341264.html