I am consuming an API that returns data in a strange way.
When a successfull request is made I get a response like this:
{
"data": {
...,
"rooms_available": [
{
"1": {
"hotel": "d9c5e4ca-1234-4321-8a97-kas123s",
"hotel_name": "Hotel name",
"history": [
{
"uuid": "d9c76322-f404-aa-b913-asd123",
"quantity": 0,
"room_id": "7b15fa32-f427-22-83bd-asd123",
"prices": {
"2023-04-13": {
"MXN": {
"regular_price_day": 0,
"member_price_day": 0,
"promotion_price_day": 0
},
"USD": {
"regular_price_day": 0,
"member_price_day": 0,
"promotion_price_day": 0
}
}
}
}
]
}
}
]
...,
}
}
I have the following model:
class MyResponse {
public Data $data;
public function __construct(Data $data) {
$this->data = $data;
}
public static function fromJson(array $data): self {
return new self(
Data::fromJson($data['data'])
);
}
}
class Data {
public array $roomsAvailable;
public function __construct(array $roomsAvailable) {
$this->roomsAvailable = $roomsAvailable;
}
public static function fromJson(array $data): self {
return new self(
array_map(static function($data) {
return RoomsAvailable::fromJson($data);
}, $data['rooms_available'])
);
}
}
I am doing the request and then I serialize the response doing:
$response = MyResponse::fromJson( $request->getContent() ); // getting the raw content of result
Everything is ok but the issue is that, for rooms_available and some other keys, it has dynamic keys like "1" or dates like "2023-04-13".
The thing is that I don't know how to represent that into a PHP object.
I am using this tool to convert JSON to PHP objects
https://jacobdekeizer.github.io/json-to-php-generator/#/
I have being using the fromJson strategy to serialize the request from the entire project and it has being going ok until now.
Which for the prices object from the respose, it generates this model:
class Prices
{
public 2023_04_13 $2023_04_13;
public function __construct(2023_04_13 $2023_04_13)
{
$this->2023_04_13 = $2023_04_13;
}
public static function fromJson(array $data): self
{
return new self(
2023_04_13::fromJson($data['2023-04-13'])
);
}
}
or the RoomsAvailable response
class RoomsAvailable
{
public 1 $1;
public function __construct(1 $1)
{
$this->1 = $1;
}
public static function fromJson(array $data): self
{
return new self(
1::fromJson($data['1'])
);
}
}
These classes are not valid due to those numbers used as keys in the JSON response.
How can I properly serialize the response into a PHP object?
I tried flatting the array one level on those nodes where there are number keys but it didn't worked.
I want to display data from SqlServer using retrofit in my custom expandable listview. How should my Json Look like to fulfill the following classes parameters?
Here is my current Json;
{"item":{"category":"electronics","items":{"title":"Ilara Milk","price":"Ksh 50","url":"http:\/\/supa.swagshop.co.ke\/Images\/coke.jpg"}}}
The following is my ShopItem class which takes String and Class Single Item in a List
public class ShopItem {
private String category;
public List<SingleItem> items = new ArrayList<SingleItem>();
public ShopItem(String category, List<SingleItem> items) {
this.category = category;
this.items = items;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<SingleItem> getItems() {
return items;
}
public void setItems(List<SingleItem> items) {
this.items = items;
}
}
Here is my Single Item class.
public class SingleItem {
private String title;
private String price;
private String url;
private Bitmap itemimage;
public SingleItem(String title, String price, String url, Bitmap itemimage) {
this.title = title;
this.price = price;
this.url = url;
this.itemimage = itemimage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Bitmap getItemimage() {
return itemimage;
}
public void setItemimage(Bitmap itemimage) {
this.itemimage = itemimage;
}
}
The following is my Main Fragment, where i'm retrieving data and displaying it on the ExpandableListView using an ExpandableListAdapter
public class MainFragment extends Fragment {
private BannerSlider bannerSlider;
private ExpandableListView CategoriesListView;
private ArrayList<ShopItem> items = new ArrayList<ShopItem>();
private ExpandableListAdapter categoryAdapter;
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
bannerSlider = (BannerSlider) view.findViewById(R.id.banner_slider1);
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
CategoriesListView = (ExpandableListView) view.findViewById(R.id.list_items);
getdata();
CategoriesListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
int previousGroup = -1;
#Override
public void onGroupExpand(int groupPosition) {
if ((previousGroup != -1) && (groupPosition != previousGroup)) {
CategoriesListView.collapseGroup(previousGroup);
}
previousGroup = groupPosition;
}
});
return view;
}
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading Items...");
progressDialog.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfaceRequest request = retrofit.create(InterfaceRequest.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccessful()){
JSONResponse jsonResponse = response.body();
items = new ArrayList<>(Arrays.asList(jsonResponse.getItem()));
categoryAdapter = new ShopItemAdapter(getContext(),items);
CategoriesListView.setAdapter(categoryAdapter);
} else {
Toasty.warning(getContext(),"Oops! Items did not load correctly", Toast.LENGTH_LONG,true).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Toasty.error(getContext(),t.getLocalizedMessage(), Toast.LENGTH_SHORT,true).show();
Log.d(Constants.TAG,t.getMessage());
progressDialog.dismiss();
}
});
}
public void showData() {
categoryAdapter = new ShopItemAdapter(getContext(),items);
CategoriesListView.setAdapter(categoryAdapter);
}
}
Based on your model class i assume that you want a category and a list of items. So you should modify your response to be in such a way like
{
"item": {
"category": "electronics",
"items": [
{
"title": "Ilara Milk",
"price": "Ksh 50",
"url": "http://supa.swagshop.co.ke/Images/coke.jpg"
}
]
}
}
If you could post a little bit of your php code, we could help you over that
As the error describes items in your json is an object items:{..} but you are trying to convert it to a list
The json should be like items: [item1, item2, ...]
I have a php json creater. That is a web service and I use it in android. I have sql datas, classes and would like run querys in clasess.
This is my json parser without classes.
<?php
/$sql_query = blabla{
$dolaplar= array();
/* fetch object array */
while ($obj = $result->fetch_object()) {
// printf ("%d - %s - %s\n", $obj->id, $obj->tanim, $obj->tipi);
$dolaplar[]= $obj;
}
$kodlanmis= json_encode($dolaplar);
echo $kodlanmis;
/* free result set */
$result->close();
}
?>
And It's json data.
[
{
malzeme_id: "9",
malzeme_adi: "10 kohm direnc",
malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]
Here is classes.
<?php
class A {
public $Message = "Success";
public $MessageInfo = "";
public $Payload = array();
function __construct(){
for ( $i=3; $i-->0;){
array_push($this->Payload, new B);
}
}
}
class B {
public $a = 3;
public $b = 4;
}
echo json_encode(new A);
?>
And I would like to see like that json data.
{
Message: "Success",
MessageInfo: "",
Payload: [
{
malzeme_id: "9",
malzeme_adi: "10 kohm direnc",
malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]
}
I am not really good about php. Is it possible ?
You could add a parameter to your Class A and Class B constructors:
Class A:
class A {
public $Message = "Success";
public $MessageInfo = "";
public $Payload = array();
function __construct($data){
foreach ($data as $d) {
array_push($this->Payload, new B($d));
}
}
}
Class B:
class B {
public function __construct($data) {
array_walk($data, function($value, $key){
$this->$key = $value;
});
}
}
Then your call would look something like:
$data = $dolapla // ???
echo json_encode(new A($data));
EDIT
Ok it seems I'm really bad at describing my problem. I found this generator on the web, and what I'm looking for it's the exact same thing but for php code. any idea ?
ORIGINAL QUESTION
I am willing to build many php classes from a json representation (API mapping to object), and to do that I'd like to convert this:
{
"success": true,
"domains": [
{
"id": "13",
"manual": "0",
"name": "silo3.mobi",
"lastname": "Doe",
"firstname": "John",
"cid": "1",
"period": "1",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "namesilo",
"next_due": "2012-12-12",
"expires": "2012-12-12",
"status": "Active",
"type": "Register",
"date_created": "2011-12-12",
"autorenew": "1",
"reglock": "1",
"idprotection": "1"
},
{
"id": "11",
"manual": "0",
"name": "netearthorg.org",
"lastname": "Doe",
"firstname": "John",
"cid": "1",
"period": "1",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "NetEarthOne",
"next_due": "2012-11-22",
"expires": "2012-11-22",
"status": "Active",
"type": "Register",
"date_created": "2011-11-22",
"autorenew": "1",
"reglock": "1",
"idprotection": "0"
},
{
"id": "10",
"manual": "0",
"name": "hbappreseller.co.uk",
"lastname": "Blue",
"firstname": "Mike",
"cid": "6",
"period": "2",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "NetEarthOne",
"next_due": "2012-11-22",
"expires": "0000-00-00",
"status": "Pending",
"type": "Register",
"date_created": "0000-00-00",
"autorenew": "1",
"reglock": "0",
"idprotection": "0"
}
],
"call": "getDomains",
"server_time": 1323793581
}
to an object with a bool:success property, an array of "domain" object and so on.
It's not that hard to do, I could develop that myself, but I'm wondering if there is some php libs that take care of that, haven't found any
EDIT
Ok I haven't explained myself so well I guess, what I'd like to do it's build a php class file, with dependencies on other classes and so on so I can match the json structure.
For instance, the given json should generate the following:
class Domain {
protected $id;
protected $manual;
protected $name;
protected $lastname;
protected $firstname;
protected $cid;
protected $period;
protected $recurring_amount;
// and so on
}
The purpose is to serve a WSDL with complex objects, and avoid making the wsdl signature evolve if any modifications are made on the original API (custom classes won't change dinamically, only when wanted so the WSDL will stay the same)
The api generate hundred of json objects, some of them sharing properties, so the purpose of this is to have a global way to handle all json strings and build or get builded objects, for example two json can have the "domains" property, so the first time I want to generate a class named Domain (if property=array then create file with property name -S and fill with attributes then save to file for further usage)
Lets say your JSON object is stored in $json, then you can create a class on the fly like this -
$data = json_decode($json, true);
$class = new Domain();
foreach ($data AS $key => $value) $class->{$key} = $value;
If you want a more generic way, let's say you want to change the class name on the fly -
$data = json_decode($json, true);
$className = "Domain"; // Or assign it to something else like pick from DB, from JSON from anywhere.
$class = new {$className}();
foreach ($data AS $key => $value) $class->{$key} = $value;
Ok, finally I found nothing to do the job of json2csharp tool, so I developed mine:
namespace Hostbill\Api\Generator;
use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Generator\PropertyValueGenerator;
use Zend\Code\Reflection\ClassReflection;
use Zend\Json\Json;
use Zend\Json\Exception\RuntimeException as JsonRuntimeException;
class DataGenerator extends AbstractGenerator
{
const DATA_NAMESPACE = 'Hostbill\Api\Data';
const RESPONSE_SUFFIX = 'Response';
const DATA_ABSTRACT_CLASS = 'AbstractData';
/**
* #var ClassGenerator[]
*/
protected $classes = array();
/**
* #var ClassGenerator
*/
protected $responseClass;
/**
* Build classes from a source json string
* #param string $json
*/
public function fromSource($json)
{
try {
$data = Json::decode($json, Json::TYPE_ARRAY);
} catch (JsonRuntimeException $e) {
$this->err(sprintf('Could not generate classes for given Json, err:"%s"', $e->getMessage()));
return;
}
$this->parse($data);
// write classes files
$this->write($this->responseClass, sprintf('%s/../Data/', __DIR__));
foreach ($this->classes as $class) {
if (self::RESPONSE_SUFFIX === substr($class->getName(), -strlen(self::RESPONSE_SUFFIX))) {
$this->write($class, sprintf('%s/../Data/Response/', __DIR__));
} else {
$this->write($class, sprintf('%s/../Data/', __DIR__));
}
}
}
/**
* Parse json decoded object and generate corresponding classes
* #param array $data associative array retrieved from json_decode
* #return DataGenerator
*/
public function parse($data)
{
$responseClassNamespace = sprintf('%s\%s', self::DATA_NAMESPACE, self::RESPONSE_SUFFIX);
// get "call" property and build Response class name on it: getClientDetails => ClientDetailResponse
$parts = preg_split('/(?=[A-Z])/', $data['call'], -1, PREG_SPLIT_NO_EMPTY);
array_shift($parts); // remove verb
$parts[] = $this->inflector()->singularize(array_pop($parts));
$parts[] = self::RESPONSE_SUFFIX;
$baseResponseClassName = sprintf('%s\%s', self::DATA_NAMESPACE, self::RESPONSE_SUFFIX);
$responseClass = new ClassGenerator(
implode('', $parts),
$responseClassNamespace,
null,
self::RESPONSE_SUFFIX
);
$responseClass->addUse($baseResponseClassName);
$this->addClass($responseClass);
if (!class_exists($baseResponseClassName)) {
$baseResponseClassGenerated = true;
$baseResponseClass = new ClassGenerator(
self::RESPONSE_SUFFIX,
self::DATA_NAMESPACE,
ClassGenerator::FLAG_ABSTRACT
);
} else {
$baseResponseClassGenerated = false;
$baseResponseClass = ClassGenerator::fromReflection(new ClassReflection($baseResponseClassName));
}
$this->responseClass = $baseResponseClass;
foreach ($data as $key => $value) {
$key = $this->inflector()->pascalize($key);
if (is_scalar($value)) {
// thoses properties belongs to the response class
// if we just have generated the "base" response class (Response.php)
// store properties there (there are only 3 basic properties: success, call, serverTime)
// otherwise store them in the child response class, but avoid any overriding of the
// 3 properties which are stored in base Response class
if ($baseResponseClassGenerated) {
$responseClassToUpdate = $baseResponseClass;
} else {
$responseClassToUpdate = $responseClass;
}
// update base response class
if (!$responseClassToUpdate->hasProperty($key) && !$baseResponseClass->hasProperty($key)) {
$responseClassToUpdate->addProperty($key);
}
} else {
// object
if ($this->isArrayAssociative($value)) {
if (!$responseClass->hasProperty($key)) {
$responseClass->addProperty($key);
}
$this->parseObject($key, $value);
// array
} else {
if (!$responseClass->hasProperty($key)) {
$responseClass->addProperty($key, new PropertyValueGenerator(array(), PropertyValueGenerator::TYPE_ARRAY));
}
// if array is simple array, do nothing
if (!is_scalar(reset($value))) {
$this->parseArrayOfObjects($key, $value);
}
}
}
}
return $this;
}
/**
* Parse ordered array and create class object
* #param string $name key name
* #param array $data
* #return DataGenerator
*/
public function parseArrayOfObjects($name, $data)
{
$class = $this->getOrCreateClass($this->inflector()->singularize($name));
foreach ($data as $object) {
foreach ($object as $key => $value) {
if (!$class->hasProperty($key)) {
$class->addProperty($key);
}
}
}
return $this;
}
/**
* Parse associative array and create class object
* #param string $name key name
* #param array $data
* #return DataGenerator
*/
public function parseObject($name, $data)
{
$class = $this->getOrCreateClass($this->inflector()->singularize($name));
foreach ($data as $key => $value) {
if (!$class->hasProperty($key)) {
$class->addProperty($key);
}
}
return $this;
}
/**
* Add class to current stack
* #param ClassGenerator $class
* #return DataGenerator
*/
protected function addClass(ClassGenerator $class)
{
$this->classes[$this->inflector()->lowerize($class->getName())] = $class;
return $this;
}
/**
* Get class from current stack
* #param string $name
* #return false|ClassGenerator False if not found
*/
protected function getClass($name)
{
$id = $this->inflector()->lowerize($name);
if (!isset($this->classes[$id])) {
return false;
}
return $this->classes[$id];
}
/**
* Try to retrievea class from current stack, create it if not found
* #param string $name
* #return ClassGenerator
*/
protected function getOrCreateClass($name)
{
if (!$class = $this->getClass($name)) {
$class = new ClassGenerator(
$this->inflector()->camelize($name),
self::DATA_NAMESPACE,
null,
self::DATA_ABSTRACT_CLASS
);
$this->addClass($class);
}
return $class;
}
/**
* Check if the given array is associative
* #param array $array
* #return bool
*/
protected function isArrayAssociative($array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
This code is so oriented for my needs, but it can easily be adapted to any json file, here the result:
JSON
{
"success": true,
"client": {
"id": "1",
"email": "jondoe#email.com",
"password": "474bf122c92de249ace867a003cb7196",
"lastlogin": "2011-11-25 04:32:40",
"ip": "213.54.21.3",
"host": "cmt-random.uk",
"status": "Active",
"parent_id": "0",
"firstname": "John",
"lastname": "Doe",
"companyname": "",
"address1": "Address 54",
"address2": "",
"city": "Soullans",
"state": "Birmingham",
"postcode": "B33 8TH",
"country": "GB",
"phonenumber": "357755733",
"datecreated": "2011-09-24",
"notes": "",
"language": "spanish",
"company": "0",
"credit": "0.00",
"taxexempt": "0",
"latefeeoveride": "0",
"cardtype": "Visa",
"cardnum": null,
"expdate": null,
"overideduenotices": "0",
"client_id": "1",
"currency_id": "0",
"countryname": "United Kingdom"
},
"call": "getClientDetails",
"server_time": 1323442995
}
GENERATED FILES (docblocks are missing but will be integrated so the WSDL is served correctly)
ClientResponse.php (base object)
namespace Hostbill\Api\Data\Response;
use Hostbill\Api\Data\Response;
class ClientResponse extends Response
{
public $clientId = null;
public $info = array(
);
}
Client.php
namespace Hostbill\Api\Data;
class Client extends AbstractData
{
public $id = null;
public $email = null;
public $password = null;
public $lastlogin = null;
public $ip = null;
public $host = null;
public $status = null;
public $parent_id = null;
public $firstname = null;
public $lastname = null;
public $companyname = null;
public $address1 = null;
public $address2 = null;
public $city = null;
public $state = null;
public $postcode = null;
public $country = null;
public $phonenumber = null;
public $datecreated = null;
public $notes = null;
public $language = null;
public $company = null;
public $credit = null;
public $taxexempt = null;
public $latefeeoveride = null;
public $cardtype = null;
public $cardnum = null;
public $expdate = null;
public $overideduenotices = null;
public $client_id = null;
public $currency_id = null;
public $countryname = null;
public $services = null;
}
I made a PHP class generator that will make models with JSON https://json2php.strikebit.io/. It will recursively inspect your JSON and make corresponding classes.
In my opinion, you should not create objects for generic data like this. You could easily map this against a generic data object.
So your framework would be just standard PHP. Like :
class JsonObject
{
protected $data = array();
public function __construct($data)
{
$this->data = $data;
}
public function __get($var)
{
if (array_key_exists($var, $this->data)) {
return $this->data[$var];
} else {
throw new Exception($var . ' not found in ' . __CLASS__);
}
}
public function __set($var, $val)
{
if (array_key_exists($var, $this->data)) {
return $this->data[$var];
} else {
throw new Exception($var . ' not found in ' . __CLASS__);
}
}
}
class Domain extends JsonObject
{
//some domain specific functionality
}
class getDomainResult
{
public $domains = array();
public $success = false;
public $lastTime = 0;
//some methods to do the calls
public function callback($result)
{
$res = json_decode($result, true);
$this->success = $res['success'];
$this->lastTime = $res['server_time'];
foreach ($res['domains'] as $domain) {
$this->domains[] = new Domain($domain);
}
}
}
I want to load the data from a JSON file into a table. (With Zend Framework)
This is my JSON file markup:
{
"wijken": {
"11": {
"coords": "3.79073170001967,51.1717753664505,0 3.79020920176376,51.1723018883706,0 3.78989543642226,51.1729670713336,0 3.78983091856725,51.1736482209016,0 3.79035112720225,51.174896701853",
"id": "kml_1",
"fid": "0",
"wijziging": "Ja",
"nieuwnr": "11",
"naam": "Noordoost",
"wijk": "Kanaaldorpen en -zone",
"wijknr": "11",
"objectid": "1",
"area": "0",
"len": "0"
}
}
I know how to do this with clear php: (and it works)
<?php
//connection to database
$$connect = mysql_connect('localhost', 'root', 'root');
$db = mysql_select_db('testdatabase');
// ALLE VELDEN LEEGMAKEN
mysql_query("TRUNCATE TABLE wijken");
// url from json file
$url = "http://data.appsforghent.be/poi/wijken.json";
//get content from json file
$json = file_get_contents($url);
// OM ALLES VAN IN DE JSON FILE TE TONENE
//var_dump(json_decode($json));
//var_dump(json_decode($json, true));
$out = json_decode($json, true);
foreach($out["wijken"] as $wijk)
{
// ID + NAAM + WIJK + WIJKNR + COORDINATEN
$coords = addslashes($wijk[coords]);
$id = addslashes($wijk[id]);
$fid = addslashes($wijk[fid]);
$wijziging = addslashes($wijk[wijziging]);
$nieuwnr = addslashes($wijk[nieuwnr]);
$naam = addslashes($wijk[naam]);
$wijk = addslashes($wijk[wijk]);
$wijknr = addslashes($wijk[wijknr]);
$objectid = addslashes($wijk[objectid]);
$area = addslashes($wijk[area]);
$len = addslashes($wijk[len]);
mysql_query("INSERT INTO wijken (coords, id, fid, wijziging, nieuwnr, naam, wijk, wijknr, objectid, area, len)
VALUES('$coords', '$id', '$fid', '$wijziging', '$nieuwnr', '$naam', '$wijk', '$wijknr', '$objectid', '$area', '$len')") or die (mysql_error());
}
?>
But how can I implement this in Zend Framework?
What I have till now in my models map in Zend Framework:
Map "DbTable" with Districts.php in it:
class Backoffice_Model_DbTable_Districts extends Zend_Db_Table_Abstract
{
protected $_name = 'Wijken';
}
District.php with getters and setters:
class Backoffice_Model_District extends Ahs_Model_Abstract
{
protected $coords;
protected $id;
protected $fid;
protected $wijziging;
protected $nieuwnr;
protected $naam;
protected $wijk;
protected $wijknr;
protected $objectid;
protected $area;
protected $len;
public function getCoords()
{
return $this->coords;
}
public function setCoords($coords)
{
$this->coords = $coords;
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getFid()
{
return $this->fidid;
}
public function setFid($fid)
{
$this->fid = $fid;
}
public function getWijziging()
{
return $this->wijziging;
}
public function setWijziging($wijziging)
{
$this->wijziging = $wijziging;
}
public function getNieuwnr()
{
return $this->nieuwnr;
}
public function setNieuwnr($nieuwnr)
{
$this->nieuwnr = $nieuwnr;
}
public function getNaam()
{
return $this->naam;
}
public function setNaam($naam)
{
$this->naam = $naam;
}
public function getWijk()
{
return $this->wijk;
}
public function setWijk($wijk)
{
$this->wijk = $wijk;
}
public function getObjectid()
{
return $this->objectid;
}
public function setObjectid($objectid)
{
$this->objectid = $objectid;
}
public function getArea()
{
return $this->area;
}
public function setArea($area)
{
$this->area = $area;
}
public function getLen()
{
return $this->len;
}
public function setLen($len)
{
$this->len = $len;
}
}
Now I have a DistrictMapper.php, but how can I implement the code to load everything from the json in my database?
What I have till now:
protected $_dbTable;
public function __construct()
{
$this->_dbTable = new Backoffice_Model_DbTable_Districts();
}
public function fetchAll()
{
$rowset = $this->_dbTable->fetchAll();
$districts = $this->_toObjects($rowset);
return $districts;
}
And now I need to make the save and toobject.
public function save(Backoffice_Model_Admin $admin)
{
$data = array('coords' => $district->getCoords(),
'id' => $district->getId(),
'fid' => $district->getFid(),
'wijziging' => $district->getWijziging(),
'nieuwnr' => $district->getNieuwnr(),
'naam' => $district->getNaam(),
'wijk' => $district->getWijk(),
'wijknr' => $district->getWijknr(),
'objectid' => $district->getObjectid(),
'area' => $district->getArea(),
'len' => $district->getLen(),
);
}
protected function _toObject(Zend_Db_Table_Row_Abstract $row = null)
{
}
From the Zend docs, Zend_DbTable::insert(), and adapted to your other posted table info:
public function save(Backoffice_Model_Admin $admin){
$data = array(
"fid": "0",
"wijziging": "Ja",
"nieuwnr": "11",
// other data from $admin...
);
$table = new Backoffice_Model_DbTable_Districts();
$table->insert($data);
}
Construct your array; pass it in.