I want to know if it's more appropriate to use a separate class (such as a factory?) to construct an object. While the code works, I am concerned about bloating of the model and the tight coupling.
To construct the said object I need:
- environment variables like api tokens
- some of the user's attributes from the model
- classes from the library
Here's the relevant snippet within my user model
that creates an AdWordsSession object for use in the third-party library:
class User extends Authenticatable {
...
public function adWordsSession($customer_id = null){
if(!$this->google_auth_token) {
return null;
}
if( $this->adWordsSesssion &&
(
(isset($customer_id) && $this->adWordsSesssion->getClientCustomerId() == $customer_id) ||
(!isset($customer_id) && $this->adWordsSesssion->getClientCustomerId() == $this->adwords_customer_id)
)
){
return $this->adWordsSesssion;
}
$oAuth2Credential = (new OAuth2TokenBuilder)
->withClientId(env('ADWORDS_CLIENT_ID'))
->withClientSecret(env('ADWORDS_CLIENT_SECRET'))
->withRefreshToken($this->google_auth_token)
->build();
$session = (new AdWordsSessionBuilder())
->withDeveloperToken(env('ADWORDS_DEVELOPER_TOKEN'))
->withUserAgent(env('ADWORDS_USER_AGENT'))
->withClientCustomerId($customer_id ?: $this->adwords_customer_id)
->withOAuth2Credential($oAuth2Credential)
->build();
$this->adWordsSesssion = $session;
return $session;
}
...
}
I am also interested to know if it applies to the reverse, using a class returned from the library (web service) to construct a model object. Should this be a static method of the model or a separate factory class. Code follows:
class AdWordsCampaign {
public static function fromAdWordsClass(Campaign $campaign, AdWordsCampaign $adWordsCampaign = null): AdWordsCampaign {
$self = $adWordsCampaign;
if(is_null($adWordsCampaign)) {
$self = new self;
$self->criterions = $self->defaultCriterions();
$self->extensions = $self->defaultExtensions();
}
if($campaign->getId()) {
$self->fieldsHelper()->id = $campaign->getId();
$self->setPublished();
}
$self->fieldsHelper()->name = $campaign->getName();
$self->fieldsHelper()->status = $campaign->getStatus();
$self->fieldsHelper()->advertisingChannelType = $campaign->getAdvertisingChannelType();
$self->fieldsHelper()->advertisingChannelSubType = $campaign->getAdvertisingChannelSubType();
$self->fieldsHelper()->budget = arrayify_object(
$campaign->getBudget() ?
$campaign->getBudget() :
CampaignFields::defaultBudget()
);
return $self;
}
}