Laravel中的Helper方法是用來建立自定義的方法,也稱為輔助方法。在之前我不太熱衷於建立自定義函式,隨著時間流轉,我開始越來越頻繁的使用它們。
什麼是Laravel助手
Laravel框架中的Helper方法其實就是普通的PHP函式,開發者可以從Laravel應用程式的任何部分來呼叫它,比如我們已經在該框架中使用內建的route(),url(),view(),dd()等方法一樣,不需要引用任何PHP檔案或者宣告任何namespace來使用,如同奇蹟般,他們可以在你的應用程式中的任何部件中使用。
接下來,我開始講述用於自定義建立輔助方法的用例。如果程式碼中多次使用了通用邏輯,可以把它們提取到輔助方法中。
我常在Blade檢視中使用輔助方法來簡化格式設定,例如在數字前新增貨幣符號,或者在特定的數字中格式化顯示,以及在應用程式中設定人性化的日期等。
建立自定義輔助方法
在Laravel中,在app目錄中建立一個檔案,然後通過composer讓應用程式啟動時自動載入。建立自定義輔助方法並非易事,在我的經驗中,將功能放在Helps.php中,然後將該檔案放在app/Utils下,實用程式工具類,你可以根據自身情況在app中任何目錄都可以。
接下來,需要將該檔案登記到位於composer.json,這個在專案根目錄的檔案中。
{
"name": "laravel/framework",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": "^7.2.5",
"ext-json": "*",
"ext-mbstring": "*",
"ext-openssl": "*",
"doctrine/inflector": "^1.4|^2.0",
"dragonmantank/cron-expression": "^2.0",
"egulias/email-validator": "^2.1.10",
"league/commonmark": "^1.3",
"league/flysystem": "^1.0.8",
"monolog/monolog": "^2.0",
"nesbot/carbon": "^2.17",
"opis/closure": "^3.1",
"psr/container": "^1.0",
"psr/simple-cache": "^1.0",
"ramsey/uuid": "^3.7|^4.0",
"swiftmailer/swiftmailer": "^6.0",
"symfony/console": "^5.0",
"symfony/error-handler": "^5.0",
"symfony/finder": "^5.0",
"symfony/http-foundation": "^5.0",
"symfony/http-kernel": "^5.0",
"symfony/mime": "^5.0",
"symfony/polyfill-php73": "^1.17",
"symfony/process": "^5.0",
"symfony/routing": "^5.0",
"symfony/var-dumper": "^5.0",
"tijsverkoyen/css-to-inline-styles": "^2.2.2",
"vlucas/phpdotenv": "^4.0",
"voku/portable-ascii": "^1.4.8"
},
"replace": {
"illuminate/auth": "self.version",
"illuminate/broadcasting": "self.version",
"illuminate/bus": "self.version",
"illuminate/cache": "self.version",
"illuminate/config": "self.version",
"illuminate/console": "self.version",
"illuminate/container": "self.version",
"illuminate/contracts": "self.version",
"illuminate/cookie": "self.version",
"illuminate/database": "self.version",
"illuminate/encryption": "self.version",
"illuminate/events": "self.version",
"illuminate/filesystem": "self.version",
"illuminate/hashing": "self.version",
"illuminate/http": "self.version",
"illuminate/log": "self.version",
"illuminate/mail": "self.version",
"illuminate/notifications": "self.version",
"illuminate/pagination": "self.version",
"illuminate/pipeline": "self.version",
"illuminate/queue": "self.version",
"illuminate/redis": "self.version",
"illuminate/routing": "self.version",
"illuminate/session": "self.version",
"illuminate/support": "self.version",
"illuminate/testing": "self.version",
"illuminate/translation": "self.version",
"illuminate/validation": "self.version",
"illuminate/view": "self.version"
},
"require-dev": {
"aws/aws-sdk-php": "^3.0",
"doctrine/dbal": "^2.6",
"filp/whoops": "^2.4",
"guzzlehttp/guzzle": "^6.3.1|^7.0",
"league/flysystem-cached-adapter": "^1.0",
"mockery/mockery": "^1.3.1",
"moontoast/math": "^1.1",
"orchestra/testbench-core": "^5.0",
"pda/pheanstalk": "^4.0",
"phpunit/phpunit": "^8.4|^9.0",
"predis/predis": "^1.1.1",
"symfony/cache": "^5.0"
},
"conflict": {
"tightenco/collect": "<5.5.33"
},
"autoload": {
"files": [
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Support/helpers.php"
],
"psr-4": {
"Illuminate\\": "src/Illuminate/"
}
},
"autoload-dev": {
"files": [
"tests/Database/stubs/MigrationCreatorFakeMigration.php"
],
"psr-4": {
"Illuminate\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "7.x-dev"
}
},
"suggest": {
"ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().",
"ext-memcached": "Required to use the memcache cache driver.",
"ext-pcntl": "Required to use all features of the queue worker.",
"ext-posix": "Required to use all features of the queue worker.",
"ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).",
"aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.0).",
"doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.6).",
"filp/whoops": "Required for friendly error pages in development (^2.4).",
"fzaninotto/faker": "Required to use the eloquent factory builder (^1.9.1).",
"guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.3.1|^7.0).",
"laravel/tinker": "Required to use the tinker console command (^2.0).",
"league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).",
"league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).",
"league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).",
"mockery/mockery": "Required to use mocking (^1.3.1).",
"moontoast/math": "Required to use ordered UUIDs (^1.1).",
"nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).",
"pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).",
"phpunit/phpunit": "Required to use assertions and run tests (^8.4|^9.0).",
"psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0).",
"symfony/cache": "Required to PSR-6 cache bridge (^5.0).",
"symfony/filesystem": "Required to create relative storage directory symbolic links (^5.0).",
"symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).",
"wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)."
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
接下來,執行composer dump-autoload並重新啟動應用程式,這樣確保Helpers.php在Laravel啟動時載入。
這樣,你可以在Helpers.php中建立一個方法,然後在應用程式中訪問呼叫此方法。
本作品採用《CC 協議》,轉載必須註明作者和本文連結