介绍在Laravel中,有介绍LaravelComposerPackage的开发,需要使用ServiceProviders。当然,开发一个扩展包对于我们Laravel开发者来说还是值得学习的。下面我们来开发一个消息通知扩展包。扩展包地址。:https://github.com/GeekGhc/LaraFlash整个包参考JeffreyWay的FlashPackages新建包。在生成的Laravel工程中新建packages目录(与app同级)然后在packages目录下新建package目录packages/geekghc/对于laraflash,我们需要到laravel工程中声明包的命名空间:"autoload":{"classmap":["database"],"psr-4":{"App\\":"app/","GeekGhc\\LaraFlash\\":"packages/geekghc/laraflash/src/"}},声明之后,不要忘记执行重新生成自动加载文件$composerdump-autoload我们需要新建一个src目录来存放我们的源文件然后因为我们在开发扩展包之后,我们需要测试和开发,所以我们生成一个composer.json文件$composerinit填写基本信息后,会在packages/geekghc/laraflash目录下生成一个composer.json文件:我给{"name":"geekghc/flash","description":"flashforlaravel","license":"MIT","authors":[{"name":"GeekGhc","email":"ghcgavin@sina.com"}],"米nimum-stability":"dev","require":{"php":">=5.5.9",},"require-dev":{"phpunit/phpunit":"~5.7","mockery/mockery":"0.9.*"},"autoload":{"psr-0":{"GeekGhc\\LaraFlash":"src/"},"files":["src/GeekGhc/LaraFlash/function.php"]}}完成composer.json后,我们就可以到src/GeekGhc/LaraFlash目录下新建Flash了。PHPapp->bind('GeekGhc\LaraFlash\SessionStore','GeekGhc\LaraFlash\LaravelSessionStore');$这个->app->singleton('laraflash',function(){return$this->app->make('GeekGhc\LaraFlash\FlashNotifier');});}这里绑定打包好的SessionStore然后我们去配置路径视图公共函数boot(){$this->loadViewsFrom(__DIR__.'/../../views','laraflash');$this->publishes([__DIR__.'/../../views'=>base_path('resources/views/vendor/laraFlash'),]);}在这里我们发布我们的视图文件如果我们执行$phpartisanvendor:publish在项目中,我们可以在resources/views/vendor/laraFlash中找到它来定制你需要的样式效果然后在config/app.php中注册我们的服务'providers'=>[GeekGhc\LaraFlash\MyFlashProvider::班级,];为了方便起见,你可以添加另一个alias'aliases'=>['LaraFlash'=>GeekGhc\LaraFlash\Flash::class,];然后我们就可以实现flash的主要功能了。每个包的功能都是根据需要来的。这里不多做介绍。最后目录结构是这样的||——packages||——geekghc||——laraflash||——src源文件||——GeekGhc源文件||——LaraFlash||——Flash.php||——FlashNotifier.php||——函数.php||——FlashProvider.php||——SessionStore.php||——LaravelSessionStore.php||——views查看文件||——tests测试目录||——测试所需的供应商包||——.gitignore||——作曲家.json||——composer.lock||——phpunit.xml||——readme.md这样,我们就在本地写好了扩展包。我们其实可以创建一个controller来测试我们的包是否正常在视图home.blade.php中我们可以在视图中包含视图文件@include('laraflash::notification')或者@include('laraflash::header-notification')然后在控制器中使用这样的形式:LaraFlash::success('Message')LaraFlash::info('Message')LaraFlash::error('Message')LaraFlash::warning('Message')For包的具体使用,去GeekGhc/LaraFlash看具体使用就知道了,最后的效果大概是这样的:显示正常后,就可以发布我们的包了。首先在github上创建一个仓库。当然我这里的是创建一个远程仓库叫LaraFlash,然后我们把我们的代码push到github上。然后我们需要到仓库的setting=>Integrations&services添加Packagist服务(填写用户名和Token)。添加后,到Packagist提交仓库(提供远程仓库地址),进入github中的packagist测试。测试通过后就ok了,因为我们之前定义在dev版本中,如果后面有人提出一些问题,你修改自己的包,那么我们会添加其他标签,也就是说,你修改包后,添加标签:$gittag2.0-a填写描述信息后,推送这个tag:$gitpush--tags这样,我们就发布了v2.0版本。这是我们发布扩展包的大致流程。博文地址LaravelPackageReferenceLaravelComposerPackageDevelopmentABriefTutorialLaravel'sExtensionsDevelopmentGuideLaravelPackageDevelopment
