前言
Laravel 提供一個 Macroable 特徵機制,用來擴展基礎類別。
Str 類別
以 Str
類別為例,新增 app/Mixins/StrMixin.php
檔:
1 | namespace App\Mixins; |
在 app/Providers/AppServiceProvider.php
檔註冊:
1 | namespace App\Providers; |
使用:
1 | echo Str::uppercase('test'); |
結果:
1 | TEST |
Collection 類別
以 Collection
類別為例,新增 app/Mixins/CollectionMixin.php
檔:
1 | namespace App\Mixins; |
在 app/Providers/AppServiceProvider.php
檔註冊:
1 | namespace App\Providers; |
使用:
1 | return collect(['test'])->uppercase()->toArray(); |
結果:
1 | ["TEST"] |
ResponseFactory 類別
以 ResponseFactory 類別為例,新增 app/Mixins/ResponseMixin.php
檔:
1 | namespace App\Mixins; |
在 app/Providers/AppServiceProvider.php
檔註冊:
1 | namespace App\Providers; |
使用:
1 | return Response::error('test'); |
結果:
1 | { |
服務提供者
新增一個 MixinServiceProvider
服務提供者來集中管理所有的 Mixin 類別。
1 | php artisan make:provider MixinServiceProvider |
修改 MixinServiceProvider
服務提供者。
1 | namespace App\Providers; |
修改 config
資料夾的 app.php
檔,以註冊服務提供者:
1 | 'providers' => [ |
補充
所有帶有巨集的類別有以下:
- Illuminate\Auth\RequestGuard
- Illuminate\Auth\SessionGuard
- Illuminate\Cache\Repository
- Illuminate\Console\Command
- Illuminate\Console\Scheduling\Event
- Illuminate\Cookie\CookieJar
- Illuminate\Database\Eloquent\FactoryBuilder
- Illuminate\Database\Eloquent\Relations\Relation
- Illuminate\Database\Grammar
- Illuminate\Database\Query\Builder
- Illuminate\Database\Schema\Blueprint
- Illuminate\Filesystem\Filesystem
- Illuminate\Foundation\Testing\TestResponse
- Illuminate\Http\JsonResponse
- Illuminate\Http\RedirectResponse
- Illuminate\Http\Request
- Illuminate\Http\Response
- Illuminate\Http\UploadedFile
- Illuminate\Mail\Mailer
- Illuminate\Routing\PendingResourceRegistration
- Illuminate\Routing\Redirector
- Illuminate\Routing\ResponseFactory
- Illuminate\Routing\Route
- Illuminate\Routing\Router
- Illuminate\Routing\UrlGenerator
- Illuminate\Support\Arr
- Illuminate\Support\Collection
- Illuminate\Support\LazyCollection
- Illuminate\Support\Str
- Illuminate\Support\Testing\Fakes\NotificationFake
- Illuminate\Translation\Translator
- Illuminate\Validation\Rule
- Illuminate\View\Factory
- Illuminate\View\View