Pest

Pest 對我來說提供了更便捷的測試方式和直譯式的寫法,類似 JS 相關的測試框架,同時又保留了 Laravel 和 PHP 龐大的輔助函數和功能。 official laracasts 主結構 $ composer require pestphp/pest --dev --with-all-dependencies $ ./vendor/bin/pest --init $ ./vendor/bin/pest folders: ├── 📂 tests │ ├── 📂 Unit │ │ └── ExampleTest.php │ └── 📂 Feature │ │ └── ExampleTest.php │ └── TestCase.php │ └── Pest.php ├── phpunit.xml 簡單示例 這邊可以自己添加 phpunit.xml 對應路徑,可以看到 Pest.php 實現細節: 這邊表示注入 TestCase 到 Feature 底下,可以使用 TestCase 裡面所提供的方法,當然也可以注入對應的方法到指定的 folder 底下: uses( Tests\TestCase::class, // Illuminate\Foundation\Testing\RefreshDatabase::class, )->in('Feature'); SumTest...

March 21, 2023 · 2 min · Yish

Laravel Eloquent Mutators

新版本的 Laravel 提供了一種更便捷的作法來定義 accessor 和 mutator,下面將會比較新舊版本之間的差異,原有方式在新版本當中還是有作兼容,但新的寫法是相對來說更加清晰好懂。 原做法 // 假定 users 有 name: // accessor protected function getNameAttribute($value) { return Str::mask($value, '*', 2); } // mutator protected function setNameAttribute($value) { $this->attributes['name'] = 'Mr.'.$value; } // 要偽裝一個不存在的欄位 accessor protected function getFirstNameAttribute($value) { return ucfirst($this->name); } 新做法 doc,將原有 accessor 和 mutator 綜合為同一個方法進行操作。 // 假定 users 有 name: protected function name(): Attribute { return Attribute::make( get: fn (string $value) => Str::mask($value, '*', 2), set: fn(string $value) => 'Mr....

March 17, 2023 · 2 min · Yish

Laravel Sail

這個工具是 Laravel 官方所提供使用 docker 作為本地開發環境的 image,這邊紀錄一下關於相關配置和安裝設定。我本地端還是有配置 Laravel Valet,所以很顯然的是我必須調整 port 和相關兼容避免 port aleady in use。 先決配置 Docker 安裝步驟 從遠端取得對應 shell script,並且執行 curl -s "https://laravel.build/<你的專案名稱>" | bash # curl -s "https://laravel.build/example-app" | bash 執行完畢後 cd 進去 開始配置對應 port -> .env,相關對應變數名稱可以參考 docker-compose.yml: APP_PORT=8088 # http port FORWARD_DB_PORT=33062 # db port FORWARD_MAILPIT_PORT=1026 # mailpit FORWARD_MAILPIT_DASHBOARD_PORT=8026 # mailpit dashboard FORWARD_REDIS_PORT=6380 # redis 拜訪 http://localhost:8088 測試相關對應數據庫連線,查看對應 .env DB_USERNAME=sail DB_PASSWORD=password 連入 app container 進行 composer 指令操作 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9463d63df32b sail-8....

March 15, 2023 · 1 min · Yish