Rumah > Artikel > pembangunan bahagian belakang > 向IOC 容器添加自己的类
从上一篇文章知道,serviceprovider是管理container的,所以在向container添加了自己的类的时候,也要注册serviceprovider来管理
需要注意的是,laravel能够对自身app目录内的php 类进行自动加载,只要是符合psr4的命名规则就行
app/Billing/Stripe.php //这里在app下建立了一个Billing目录,里面放了一个Stripe的类< ?phpnamespace App\Billing; //需要命名空间才能被php正确查找到class Stripe{ public function charge(){ dd('charge'); }}
用这个命令创建
php artisan make:provider BillingServiceProvider
app/Providers/BillingServiceProvider.php //创建成功后会在这个目录生成php文件<?phpnamespace App\Providers;use App\Billing\Stripe;use Illuminate\Support\ServiceProvider;class BillingServiceProvider extends ServiceProvider{ /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('billing',function(){ //这里用了bind方法来创建一个container,绑定了一个billing的关键字来关联,这个container里会返回一个Stripe实例,相当于实例化了。 return new Stripe(); }); }}
在app.php里注册了才能被laravel识别这个service provider,才能在代码里面调用
config/app.php 'providers' => [ //在providers数组里面添加 /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, Collective\Html\HtmlServiceProvider::class, 'Maatwebsite\Excel\ExcelServiceProvider', /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\BillingServiceProvider::class, //按照格式添加即可 ],
主要是为了测试目的,所以在路由里面直接来测试service provider
app/Http/routes.php//这里有两种方式使用,第一种是跟上一篇文章提到的两种container使用方式有关,第二种是通过自动解析机制来实现//Route::get('/', function () {// $billing = app('billing'); //用直接传入关键字,也可以用make()// dd($billing->charge());//});Route::get('/', function (App\Billing\Stripe $billing) { //传入一个class名字和一个变量,laravel会自动去寻找和解析 dd($billing->charge());});