Laravel經常使用包整理

Carbon

  • PHP事實上的標準時間處理包
  • 面向對象的角度來進行時間方面的處理工做
  • 其解決了諸多時間處理上的疑難雜症
$now = Carbon::now();
$now->format('Y-m-d H:i:s');

$tomorrow = Carbon::tomorrow();
$tomorrow->addDays(3);
$tomorrow->diffInDays($now);

$sometime = Carbon::parse('2017-01-01');

GuzzleHttp

  • PHP事實上的Http請求標準

使用示例php

$httpClient = new \GuzzleHttp\Client([
            'timeout' => 5,
            'http_errors' => false, //忽略掉請求錯誤
            'headers' => [
                'Accept' => 'application/json',
            ],
        ]);

# Get請求(query字符串)
$httpClient->get('http://example.com/api', [query => $data])

# Post請求(表單數據)
# $data數組自動編碼爲`application/x-www-form-urlencoded`形式
$httpClient->post('http://example.com/api', [form_params => $data])

# Post請求(Json數據)
# $data數組自動編碼爲json字符串
$httpClient->post('http://example.com/api', [json => $data]) 

## Promise異步併發請求
$promises = [
	$httpClient->requestAsync('POST', 'http://example.com/apixx', [json => $data]),
	$httpClient->requestAsync('POST', 'http://example.com/apiyy', [json => $data]),
];
$responses = Promise\settle($promises)->wait();

laravel-ide-helper

phpDoc自動完成laravel

## 安裝 ##
composer require barryvdh/laravel-ide-helper:~2.2 --dev

## AppServiceProvider中註冊 ##
public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

## 輸出配置文件 ##
php artisan vendor:publish --provider="Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider" --tag=config


## 輸出phpDocs支持文件/_ide_helper.php,加強IDE的自動提示 ##
# 編輯 config/ide-helper.php
	# 默認只輸出facade註解
	'include_helpers' => true, # helper函數註解支持
	'include_fluent' => true, # migration中鏈式調用註解支持
php artisan clear-compiled  # 清理bootstrap/compiled.php
php artisan ide-helper:generate  # 自動完成Facades的註解(須要常常執行,項目根下會導出_ide_helper.php文件)
php artisan optimize  # 重建bootstrap/compiled.php
# 編輯composer.json實現每次`composer update nothing`後自動刷新phpDocs支持文件
	"scripts":{
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "composer dump-autoload --optimize",
            "php artisan clear-compiled",
            "php artisan ide-helper:generate",
            "php artisan ide-helper:meta",
            "php artisan optimize"
        ]
	},


## 輸出模型類字段註解 ##
# 首先調通數據庫鏈接
composer require Doctrine/dbal:^2.5 --dev  #用於獲取數據表列的定義
php artisan ide-helper:models --write ["\\完整命名空間模型"]


## 輸出PhpStorm Meta,提供IOC容器提示支持 ##
php artisan ide-helper:meta  # 項目根下會導出.phpstorm.meta.php文件

## lumen框架下安裝 ##
# 編輯bootstrap/app.php啓用以下幾行
$app->withFacades();
$app->register(App\Providers\AppServiceProvider::class);

laravel-debugbar

## 提供如下數據收集器 ##
* 可定製collector:`QueryCollector、RouteCollector、ViewCollector、EventsCollector、LaravelCollector、SymfonyRequestCollector、LogsCollector、FilesCollector、ConfigCollector`
* Laravel啓用collector:`LogCollector、SwiftMailCollector、SwiftLogCollector`
* 默認collector:`PhpInfoCollector、MessagesCollector、TimeDataCollector、MemoryCollector、ExceptionsCollector`

## 安裝 ##
composer require barryvdh/laravel-debugbar:^2.3 --dev

# 註冊在config/app.php中
'providers' => [Barryvdh\Debugbar\ServiceProvider::class, ...]
'aliases' => ['Debugbar' => Barryvdh\Debugbar\Facade::class, ...]

# 發佈包配置文件
php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

# 使用
Debugbar::enable|disable();
Debugbar::info|error|warning|addMessage();
Debugbar::startMeasure|stopMeasure|addMeasure|measure();
debug($var, ...);

Incoming

可定製的將鬆散輸入數據hydrate到對象(fractal的逆向過程)git

## 安裝 ##
composer require incoming/incoming=^0.2.1

## 使用 ##
class MyModelHydrator implements Incoming\Hydrator\HydratorInterface
{
    public function hydrate($input, $model)
    {
	    # 能夠作一些輸入數據校驗邏輯
        $model->setName($input->name);
        return $model;
    }
}

$incoming = new Incoming\Processor();
$hydratedModel = $incoming->process(
    app('request')->all(),
    $myModel,
    $myModelHydrator
);

Fractal

相關概念github

序列化

PHP領域廣受歡迎的API數據輸出格式轉換器ajax

  • 支持 單個對象 或者 集合對象 的格式化
  • 經過Fractal Transformer顯式修飾對象的數據輸出,將複雜數據轉爲ajax/restful
  • 額外特性
    • 關聯數據的Include動態加載
    • 數據載荷轉換到各類協議格式:JSONDataArrayHAL等等
  • 友好的和DingoApi無縫結合

對於WEB站來講數據庫

  • 不建議過多進行數據格式化,直接輸出完整對象,儘可能用對象來替代數組
  • 特別的字段值計算能夠封裝爲對象的方法

原生使用json

class MyTransformer extends League\Fractal\TransformerAbstract
{
	# normalize主邏輯
	public function transform($object){
		return [
			'id' => $object->id,
			'name' => $object->name,
		];
	}
	
    ## include特性 ##
    ## 使用前須要檢測include參數:$manager->parseIncludes($_GET['include']);
    protected $defaultIncludes = []; #聲明須要默認include的資源
    protected $availableIncludes = [tag]; #聲明可選include資源
    public function includeTag($object){
        $tag = $object->tag;
        return $this->item($tag, new TagTransformer);  #包含單對象
        #return $this->collection($tags, new TagTransformer); #包含集合對象
    }
}

$itemResource = new \Fractal\Resource\Item(
	$object,
	League\Fractal\TransformerAbstract $myTransformer
);
$collectionResource = new \Fractal\Resource\Collection(
	$objects,
	League\Fractal\TransformerAbstract $myTransformer
);

$manager = new League\Fractal\Manager();
$manager = $manager->createData($itemResource|$collectionResource)->toArray|toJson(); #transformer轉換數據
# 能夠進一步使用serializer在toArray()輸出前調整數據結構

LaravelFractal使用bootstrap

  • 安裝Fractal驅動spatie/laravel-fractal
class BookTransformer extends League\Fractal\TransformerAbstract
{
    # normalize邏輯
    public function transform($object){
        return [
            'id' => $object->id,
            'name' => $object->name,
        ];
    }
}

# 集合對象序列化(兩種寫法)
- Fractal::collection($books)->transformWith(new BookTransformer())->toArray();
- fractal($books, new BookTransformer())->toArray();

# 單個對象序列化(兩種寫法)
- Fractal::item($book)->transformWith(new BookTransformer())->toArray();
- fractal($book, new BookTransformer())->toArray();

JsonMapper

自動根據類phpdoc @varsetterTypehint將接口JSON數據hydrate映射到類對象上api

  • 映射到模型上便於封裝方法
  • 接口變動只需調整數據模型,不用調整業務代碼
  • 有以上特性帶來的IDE自動完成能力
## 安裝 ##
composer require netresearch/jsonmapper=^1.0

## 使用 ##
$mapper = new JsonMapper();
$mapper->classMap['AaClass'] = 'BbClass'; #微調映射處理的類型(AaClass是抽象類時)
$mapper->bStrictNullTypes = false;  #設置容許json字段爲空
$mapper->bExceptionOnUndefinedProperty = false;
$mapper->bExceptionOnMissingData = true;
$mapper->bIgnoreVisibility = true;
$mapper->bStrictObjectTypeChecking = true;
$mapper->bEnforceMapType = true;

$myModel= $mapper->map(Object $jsonData, new MyModel());  # 單一對象映射
$myModels= $mapper->mapArray($jsonDataList, array()|Collection, 'MyModel');  # 一組對象映射

Ultraware/Roles

Laravel5 RBAC權限系統數組

## 安裝 ##
composer require ultraware/roles:~5.4

# 發佈配置和數據庫遷移
php artisan vendor:publish --provider="Ultraware\Roles\RolesServiceProvider" --tag=config
php artisan vendor:publish --provider="Ultraware\Roles\RolesServiceProvider" --tag=migrations
php artisan migrate

# config/app.php中註冊providor
'providers' => [
    Ultraware\Roles\RolesServiceProvider::class,
    ...
]

# User模型調整
- implements \Ultraware\Roles\Contracts\HasRoleAndPermission;
- use \Ultraware\Roles\Traits\HasRoleAndPermission;

## 使用 ##
$testRole = Role::create(['name'=>xx, 'slug'=>yy]);
$user->attachRole|detachRole($testRole);
$user->detachAllRoles();
$user->syncRoles($roles);
$user->isTestRole(); //魔術調用
$user->hasRole($testRole->slug|$testRoles->slugs [,boolAllMatch]);

$user->level();

$testPermission = Permission::create(['name'=>xx, 'slug'=>yy]);
$role|$user->attachPermission|detachPermission($testPermission);
$role|$user->detachAllPermissions();
$role|$user->syncPermissions($permissions);
$user->hasPermission($testPermission->slug);
$user->canTestPermission(); //魔術調用

# 權限繼承:上層level的role擁有全部下層level role的權限

# 實體檢查
$user->allowed($testPermission->slug, $entity [, boolOwnerCheck]);

# blade拓展
- @role($testRole->slug [,boolAllMatch])...@else...@endrole
- @level($testRole->level)...@else...@endlevel
- @permission($testPermission->slug)...@else...@endpermission
- @allowed($testPermission->slug, $entity)...@else...@endallowed

## 路由中權限約束 ##
# app/Http/Kernel.php中註冊路由中間件
protected $routeMiddleware = [
	...
    'role' => \Ultraware\Roles\Middleware\VerifyRole::class,
    'permission' => \Ultraware\Roles\Middleware\VerifyPermission::class,
    'level' => \Ultraware\Roles\Middleware\VerifyLevel::class,
]

# 路由中調用約束
$router->middleware(role:testrole);
$router->middleware(permission:testpermission);
$router->middleware(level:testlevel);

#校驗失敗時拋出如下異常
- \Ultraware\Roles\Exceptions\RoleDeniedException
- \Ultraware\Roles\Exceptions\PermissionDeniedException
- \Ultraware\Roles\Exceptions\LevelDeniedException

Eloquence

EloquentORM功能加強

* `composer require sofa/eloquence:~5.3`
* `bootstrap/app.php`中註冊`Sofa\Eloquence\ServiceProvider`
* Model引入特性Trait(順序重要)

#### Eloquence Trait加強 ####
# 助手方法
CustomModel::hasColumn($colName)
CustomModel::getColumnListing()

# hooks
class CustomModel extends Model
{
  use Eloquence;
  use Mappable, Mutable;

  protected $maps = ['name' => 'profile.name'];
  protected $getterMutators = ['name' => 'ucwords'];
  protected $setterMutators = ['name' => 'strtolower'];
}
  • oss驅動實現github.com/tyua07/laravel-upload
相關文章
相關標籤/搜索