April 15, 2018 —John Koster
The with
is a useful utility function that can be used to simply return the provided values back to the caller. This can be used as an entry point for method chaining without the need to create temporary local variables.
It is also possible to supply a callback function that will accept the provided value as its first, and only argument.
The signature of the with
function is:
1function with(2 $value,3 callable $callback = null4);
The with
function can be used to simply return the supplied $value
. This function can be used to invoke methods on new class instances that are passed as function arguments:
1<?php 2 3class ExampleClass { 4 5 public function someMethod() 6 { 7 return 'some value'; 8 } 9 10 // Other methods.11 12}13 14$value = with(new ExampleClass)->someMethod();
In the above example, $value
would be contain the value some value
.
A>## Alternative to the with
Function
The same effect provided by the with
function can be accomplished using vanilla PHP. The technique is to wrap object instantiation within a pair of parenthesis ((
and )
):
$value = (new ExampleClass)->someMethod();
Again, the value of $value
would be some value
. Both vanilla PHP method and the with
method are perfectly capable. However, the with
function may help to improve readability and clarify intent.
Another useful way to interact with the with
function is to take advantage of the $callback
parameter. This allows you to perform additional actions, or mutate the value before it is returned.
In the following example, we will use this to get a weather forecast using the Yahoo weather API.
1/** 2 * Returns a weather forecast for a given place. 3 * 4 * @param string $place 5 * @return \Illuminate\Support\Collection 6 */ 7function getWeatherForecast($place) { 8 return with($place, function ($place) { 9 $apiUrl = 'https://query.yahooapis.com/v1/' .10 'public/yql?q=select%20*%20from%20weather.' .11 'forecast%20where%20woeid%20in%20(select' .12 '%20woeid%20from%20geo.places(1)%20where' .13 '%20text%3D%22<PLACE>%22)&format=json&env=' .14 'store%3A%2F%2Fdatatables.org' .15 '%2Falltableswithkeys';16 17 $apiUrl = str_replace(18 '<PLACE>',19 $place,20 $apiUrl21 );22 23 return with(24 new GuzzleHttp\Client,25 function ($client) use ($apiUrl) {26 /** @var GuzzleHttp\Client $client */27 $response = $client->get($apiUrl);28 $responseBody = $response->getBody();29 $result = json_decode(30 $responseBody31 ->getContents()32 );33 34 // Get the forecast.35 return collect(36 $result->query->results37 ->channel->item38 ->forecast39 );40 });41 });42}
We can now invoke our demo getWeatherForecast
function like so to get the forecast for any provided location:
1use Illuminate\Support\Str; 2 3// Get the weather forecast for San Francisco, CA 4$forecast = getWeatherForecast('San Francisco, CA'); 5 6// Get the cloudy days. 7$cloudyDays = $forecast->filter(function ($forecast) { 8 return Str::contains( 9 $forecast->text,10 'Cloudy'11 );12});
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.