Skip to content

Instantly share code, notes, and snippets.

@Danack
Created March 20, 2020 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danack/3d2504be1d593ebf63185870d1edb8d5 to your computer and use it in GitHub Desktop.
Save Danack/3d2504be1d593ebf63185870d1edb8d5 to your computer and use it in GitHub Desktop.
two interfaces
<?php
declare(strict_types = 1);
class NameAndAge
{
private int $age;
private string $name;
/**
*
* @param int $age
* @param string $name
*/
public function __construct(int $age, string $name)
{
$this->age = $age;
$this->name = $name;
}
/**
* @return int
*/
public function getAge(): int
{
return $this->age;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
}
interface UserDataMapper
{
public function mapUserData(UserDataDto $userData): array;
}
interface ClientDataMapper
{
public function mapClientData(ClientDataDto $clientDataDto): array;
}
class UserDataMapper implements UserDataMapper, ClientDataMapper
{
private function mapNameAndAge(NameAndAge $userData): array
{
//whatever processing is not included in the example done here.
}
public function mapUserData(UserDataDto $userData): array
{
$nameAndAge = new NameAndAge(
$userData->getName() ?? 'Fred',
$userData->getAge ?? 0
);
return $this->mapNameAndAge($nameAndAge);
}
public function mapClientData(ClientDataDto $clientDataDto): array
{
$nameAndAge = new NameAndAge(
$clientDataDto->getName() ?? 'Fred',
$clientDataDto->getAge ?? 0,
);
return $this->mapNameAndAge($nameAndAge);
}
}
// USAGE OF MAPPER CLASS
class SomeUserController
{
// dependenc on UserDataMapper
public function someUserMethod()
{
$userDataDto = // get user data from DB and set UserDataDto object
$mappedUserData = $this->userDataMapper->mapUserData($userDataDto);
}
}
// I WANT TO DO RESUSE MAPPER CLASS WITH NEW OBJECT
class SomeClientController
{
// Dependency on ClientDataMapper
public function someClientMethod()
{
$clientDataDto = // get client data from DB and set ClientDataDto object
$mappedClientData = $this->clientDataMapper->mapClientData($clientDataDto);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment