Skip to content

Instantly share code, notes, and snippets.

@demirhanali
Created August 20, 2020 11:19
Show Gist options
  • Save demirhanali/7cbb19b161e2069580d64d7f90e25a27 to your computer and use it in GitHub Desktop.
Save demirhanali/7cbb19b161e2069580d64d7f90e25a27 to your computer and use it in GitHub Desktop.
<?php
interface DataType
{
/**
* @return mixed
*/
public function getModel();
}
class StringType implements DataType
{
/**
* @var array
*/
public $model;
/**
* StringType constructor.
* @param array $model
*/
public function __construct(array $model)
{
$this->model = $model;
}
/**
* @return mixed|string
*/
public function getModel()
{
return implode(", ", $this->model);
}
}
class JsonType implements DataType
{
/**
* @var array
*/
public $model;
/**
* JsonType constructor.
* @param array $model
*/
public function __construct(array $model)
{
$this->model = $model;
}
/**
* @return false|string
*/
public function getModel()
{
return json_encode($this->model, true);
}
}
class TypeFactory
{
/**
* @var array
*/
public $model;
/**
* TypeFactory constructor.
* @param array $model
*/
public function __construct(array $model)
{
$this->model = $model;
}
/**
* @param string $type
* @return DataType
*/
public function setType(string $type) : DataType
{
switch ($type) {
case "Json":
return new JsonType($this->model);
case "String":
return new StringType($this->model);
}
}
}
class Client
{
public function getResponse()
{
$model = array(
"name" => "Jane",
"age" => 31
);
$typeCreator = new TypeFactory($model);
$response = $typeCreator->setType("String");
return $response->getModel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment