Created
August 22, 2024 18:13
-
-
Save atakde/4a0d898b6d7b24eeee6ac7d564159a2a to your computer and use it in GitHub Desktop.
Builder pattern example in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class URLBuilder | |
{ | |
private $url; | |
private $source; | |
private $medium; | |
private $campaign; | |
private $term; | |
public function __construct($url) | |
{ | |
$this->url = $url; | |
} | |
public function setSource($source) | |
{ | |
$this->source = $source; | |
return $this; | |
} | |
public function setMedium($medium) | |
{ | |
$this->medium = $medium; | |
return $this; | |
} | |
public function setCampaign($campaign) | |
{ | |
$this->campaign = $campaign; | |
return $this; | |
} | |
public function setTerm($term) | |
{ | |
$this->term = $term; | |
return $this; | |
} | |
public function build() | |
{ | |
$query = http_build_query([ | |
'utm_source' => $this->source, | |
'utm_medium' => $this->medium, | |
'utm_campaign' => $this->campaign, | |
'utm_term' => $this->term | |
]); | |
return sprintf('%s?%s', $this->url, $query); | |
} | |
} | |
$utmUrlBuilder = (new URLBuilder('https://www.example.com')) | |
->setSource('blog') | |
->setMedium('any') | |
->setCampaign('summer_sale') | |
->setTerm('shoes'); | |
echo $utmUrlBuilder->build(); | |
// Output: https://www.example.com?utm_source=blog&utm_medium=any&utm_campaign=summer_sale&utm_term=shoes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment