This is part of the series tinker like a boss (in psysh)
Helpers
You may find yourself in need of some handy shortcuts when tinkering. I often need to make an HTTP call or run a quick test request, that works exactly as the one you’d run in your Laravel tests.
Something like this should come in handy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php // Call the world out there >>> http('https://softonsofa.com') => GuzzleHttp\Psr7\Response {#9121} >>> $response = http()->post('https://your.url/an-endpoint', ['json' => $payload]) => GuzzleHttp\Psr7\Response {#9121} // Or play with your local app >>> local('a-route-in-your/local-laravel-app')->getStatusCode() => 200 >>> local('/') => Illuminate\Foundation\Testing\TestResponse {#22400 +baseResponse: Illuminate\Http\Response {#22622 +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#22719}, +original: Illuminate\View\View {#22721}, +exception: null, }, } // or whatever else you may want >>> gh_stars('jarektkaczyk') => 1000 |
Using already mentioned .tinker
include file or the global config for your psysh installtion, you can easily create such shortcuts all that you may need:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php class _LocalRequest extends \Tests\TestCase { function __construct() { $this->setUp(); } function response() { return $this->response; } function __call($method, $params) { return call_user_func_array([$this, $method], $params); } } if (!function_exists('local')) { function local($uri = null) { return $uri ? (new _LocalRequest)->get($uri) : new _LocalRequest; } } if (!function_exists('http')) { function http($url = null) { return $url ? (new GuzzleHttp\Client)->get($url) : new \GuzzleHttp\Client; } } |
If you didn’t check it yet, here is the psysh config file that I prepared for you.
Enjoy and share your thoughts in the comments below or on twitter @SOFTonSOFA
Now is the time to go to your console, type $ php artisan tinker
and follow along
Laravel – tinker like a boss with PsySH from Jarek on Vimeo.