1、通过 Composer 创建项目
composer create-project --prefer-dist laravel/laravel pkg
2、新建目录
接着进入此项目中,创建目录 packages/{your_name}/{your_package_name}
mkdir -p packages/you_name/unlimited
然后再进入扩展包目录,进行 composer
初始化:
cd packages/everan/unlimitedclassified composer init
按着提示来输入信息,得到的 comoposer
内容大概如下:
{ "name": "dyn/unlimited", "description": "This is a unlimited classified", "type": "project", "autoload": { "psr-4": { "Dyn\\Unlimited\\": "src/" } }, "authors": [ { "name": "dyn" } ], "minimum-stability": "dev", "require": {} }
此时扩展包目录大致如下:
dyn/unlimited ├── src # 逻辑代码文件夹 ├── tests # 测试用例文件夹 ├── README.md ├── composer.json
在src下创建config 目录来存取我们的配置参数文件如config/unlimited.php
<?php return [ 'parent_key' => 'pid', 'child_key' => 'child', ]; ?>
3、编写扩展包业务逻辑代码
src 目录创建 Unlimited.php 具体代码
<?php namespace Dyn\Unlimited; use Illuminate\Config\Repository; class Unlimited { protected $config; /** * 构造方法 */ public function __construct(Repository $config) { $this->config = $config->get('unlimited'); } public function getUnlimited($data) { $parent_key=$this->config['parent_key']; $child_key=$this->config['child_key']; $data = array_column($data, null, 'id'); $tree = []; foreach ($data as $key => $val) { if ($val[$parent_key] == 0) { $tree[] = &$data[$key]; } else { $data[$val[$parent_key]][$child_key][] = &$data[$key]; } } return $tree; } }
在src创建UnlimitedProvider.php即服务提供者。供ioc容器注册
<?php namespace Dyn\Unlimited; use Illuminate\Support\ServiceProvider; class UnlimitedProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // 发布配置文件 $this->publishes([ __DIR__.'/config/unlimited.php' => config_path('unlimited.php'), ]); } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('unlimited', function ($app) { return new Unlimited($app['config']); }); } }
如果想使用门脸,可以在src目录下创建Facades目录,提供门脸
<?php namespace Dyn\Unlimited\Facades; use Illuminate\Support\Facades\Facade; class Unlimited extends Facade { protected static function getFacadeAccessor() { return 'unlimited'; } }
使用扩展包
到这里扩展包就基本算开发好了,接下来我们开始进行本地安装和测试。
本地测试
手动把服务类 UnlimitedServiceProvider
添加到项目的 config/app.php
providers 数组中:
'providers' => [ · · · Dyn\Unlimited\UnlimitedProvider::class, ], 'aliases' => [ · · · 'Unlimited' => Dyn\Unlimited\Facades\Unlimited::class, ],
接着修改根目录里的 composer
的配置pkg/composer.json
"autoload": { · · "psr-4": { · · "Dyn\\Unlimited\\": "packages/dyn/unlimited/src/" } },
发布配置文件在config目录下面
php artisan vendor:publish
最后在根目录执行命令:
composer dump-autoload
测试
根目录执行
php artisan tinker
接着输入代码:
$data = [ ['id'=>1,'pid'=>0,'name'=>1], ['id'=>2,'pid'=>0,'name'=>2], ['id'=>3,'pid'=>1,'name'=>3], ['id'=>4,'pid'=>2,'name'=>4], ['id'=>5,'pid'=>3,'name'=>5], ['id'=>6,'pid'=>4,'name'=>6], ['id'=>7,'pid'=>5,'name'=>7], ['id'=>8,'pid'=>6,'name'=>8], ]; app('unlimited')->getUnlimited($data);
标签:laravel,name,扩展,pid,unlimited,key,composer,config From: https://www.cnblogs.com/blog-dyn/p/17074666.html