- 前面已经写了composer拓展包的开发,基本可以开发出一个通用的拓展包,在laravel中很多拓展的包都是通过门面来使用,这里就简单的看看laravel的拓展包如何编写
- composer拓展包开发
- composer拓展包开发(二)自动更新与版本控制
引入拓展包
这里使用的laravel版本为5.6版本,引入我们前面已经开发好的拓展包
composer require superkingm/math v2.0
在控制器中进行简单的使用,这里在编辑器里面能够显示参数,并且能有提示
在vendor\superkingm
文件夹中能找到我们的拓展包,拓展包非常的简单,只有一个Math
类
改造成laravel拓展包
上面是原始的composer拓展包,我们需要在控制器中先要进行实例化才能进行使用。在laravel的门面中,是可以直接的进行使用,这里我们就改造成laravel门面的方式进行调用。
直接在laravel项目中改造我们的拓展包,因为要继承laravel 的服务和门面,在项目中比较好开发,开发完毕后,我们再独立出来,提交我们的拓展包
使用laravel中的门面需要我们先注册服务的方式来实例化类,再使用门面在服务中调用
- 新建服务在Math文件夹下新建
Provider
文件夹,并新建服务MathServiceProvider.php
<?php
namespace Math\Provider;
use Illuminate\Support\ServiceProvider;
use Math\Math;
class MathServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('math', function ($app) {
return new Math();
});
}
}
新建门面Math.php
<?php
namespace Math\Provider;
use Illuminate\Support\Facades\Facade;
class Math extends Facade
{
protected static function getFacadeAccessor()
{
return 'math';
}
}
在config\app.php
中providers
和aliases
中分别进行配置
\Math\Provider\MathServiceProvider::class,
‘Math’ =>\Math\Provider\Math::class
控制器中使用
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Math;
class IndexController extends Controller
{
public function index()
{
return Math::sum(1, 3);
}
}
拓展包提交与使用
我们将开发好的拓展包在vendor
文件夹进行提取出来进行提交到github仓库,详细见前面所提到的。
我们使用我们已经开发好的拓展包来验证是否成功
composer require superkingm/math v3.0
在config\app.php中进行配置,并在控制器中使用
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Math;
class IndexController extends Controller
{
public function index()
{
return [Math::sum(1, 3),Math::sub(87,12),Math::mult(7,8),Math::div(56,7)];
}
}
到此我们适合laravel门面的拓展包就已经开发完毕了