I’m trying to implement what I believe is a factory class. I have an API framework. After my front controller has processed the request it attempts to return the output to the client. The call in my front controller looks like this:
<?php
...
$response_obj = new Response($response_str, 'json');
echo $response_obj->render();
?>
My Response class basically takes the second argument as the type of class to instantiate, and passes this new class the contents of $response_str. Here it is:
<?php
class Response {
public function __construct($data, $format) {
switch ($format) {
case 'json':
$obj = new ResponseJson($data);
break;
}
return $obj;
}
}
And then my ResponseJson class looks as follows:
<?php
class ResponseJson {
protected $data;
public function __construct($data) {
$this->data = $data;
return $this;
}
public function render() {
header('Content-Type: application/json');
return json_encode($this->data);
}
}
However, in my front controller $response_obj returns its type as Response and not ResponseJson as would be expected, and a call to the render() method (which exists in ResponseJson and not Response) throws a Fatal error:
Fatal error: Call to undefined method Response::render() in /Users/Martin/Sites/api-framework/index.php on line 61
Where am I going wrong?
what you describe is not a factory, but rather invalid code. (the __construct will always return a new instance of the class it is implemented in. in fact, it does not need to return anything because this has no effect!)
A factory is usually implemented as a static function that can be called without instantiating an object of the factory class. It then creates an object instance of a class (in most cases of another class, as in your case) and returns that.
your Response class should look like this:
and your frontend controller like this: