Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray or whatever it is, but that will create a new stdClass and doesn't help me much. Are there any easy one or two line methods to make each $key => $value pair in my array into a $key = $value variable for my class? I don't find it very logical to use a foreach loop for this, I'd be better off just converting it to a stdClass and storing that in a variable, wouldn't I?
class MyClass {
var $myvar; // I want variables like this, so they can be references as $this->myvar
function __construct($myarray) {
// a function to put my array into variables
}
}
This simple code should work:
<?php
class MyClass {
public function __construct(Array $properties=array()){
foreach($properties as $key => $value){
$this->{$key} = $value;
}
}
}
?>
Example usage
$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"
Alternatively, this might be a better approach
<?php
class MyClass {
private $_data;
public function __construct(Array $properties=array()){
$this->_data = $properties;
}
// magic methods!
public function __set($property, $value){
return $this->_data[$property] = $value;
}
public function __get($property){
return array_key_exists($property, $this->_data)
? $this->_data[$property]
: null
;
}
}
?>
Usage is the same
// init
$foo = new MyClass(array("hello" => "world"));
$foo->hello; // => "world"
// set: this calls __set()
$foo->invader = "zim";
// get: this calls __get()
$foo->invader; // => "zim"
// attempt to get a data[key] that isn't set
$foo->invalid; // => null
Best solution is to have trait with static function fromArray that can be used for data loading:
trait FromArray {
public static function fromArray(array $data = []) {
foreach (get_object_vars($obj = new self) as $property => $default) {
if (!array_key_exists($property, $data)) continue;
$obj->{$property} = $data[$property]; // assign value to object
}
return $obj;
}
}
Then you can use this trait like that:
class Example {
use FromArray;
public $data;
public $prop;
}
Then you can call static fromArray function to get new instance of Example class:
$obj = Example::fromArray(['data' => 123, 'prop' => false]);
var_dump($obj);
I also have much more sophisticated version with nesting and value filtering https://github.com/OzzyCzech/fromArray
if you (like me) came here looking for a source code generator for array->class, i couldn't really find any, and then i came up with this (a work in progress, not well tested or anything, json_decode returns the array.):
<?php
declare(strict_types = 1);
$json = <<<'JSON'
{"object_kind":"push","event_name":"push","before":"657dbca6668a99012952c58e8c8072d338b48d20","after":"5ac3eda70dbb44bfdf98a3db87515864036db0f9","ref":"refs/heads/master","checkout_sha":"5ac3eda70dbb44bfdf98a3db87515864036db0f9","message":null,"user_id":805411,"user_name":"hanshenrik","user_email":"divinity76#gmail.com","user_avatar":"https://secure.gravatar.com/avatar/e3af2bd4b5604b0b661b5e6646544eba?s=80\u0026d=identicon","project_id":3498684,"project":{"name":"gitlab_integration_tests","description":"","web_url":"https://gitlab.com/divinity76/gitlab_integration_tests","avatar_url":null,"git_ssh_url":"git#gitlab.com:divinity76/gitlab_integration_tests.git","git_http_url":"https://gitlab.com/divinity76/gitlab_integration_tests.git","namespace":"divinity76","visibility_level":0,"path_with_namespace":"divinity76/gitlab_integration_tests","default_branch":"master","homepage":"https://gitlab.com/divinity76/gitlab_integration_tests","url":"git#gitlab.com:divinity76/gitlab_integration_tests.git","ssh_url":"git#gitlab.com:divinity76/gitlab_integration_tests.git","http_url":"https://gitlab.com/divinity76/gitlab_integration_tests.git"},"commits":[{"id":"5ac3eda70dbb44bfdf98a3db87515864036db0f9","message":"dsf\n","timestamp":"2017-06-14T02:21:50+02:00","url":"https://gitlab.com/divinity76/gitlab_integration_tests/commit/5ac3eda70dbb44bfdf98a3db87515864036db0f9","author":{"name":"hanshenrik","email":"divinity76#gmail.com"},"added":[],"modified":["gitlab_callback_page.php"],"removed":[]}],"total_commits_count":1,"repository":{"name":"gitlab_integration_tests","url":"git#gitlab.com:divinity76/gitlab_integration_tests.git","description":"","homepage":"https://gitlab.com/divinity76/gitlab_integration_tests","git_http_url":"https://gitlab.com/divinity76/gitlab_integration_tests.git","git_ssh_url":"git#gitlab.com:divinity76/gitlab_integration_tests.git","visibility_level":0}}
JSON;
$arr = json_decode ( $json, true );
var_dump ( array_to_class ( $arr ) );
/**
*
* #param array $arr
* #param string $top_class_name
*/
function array_to_class(array $arr, string $top_class_name = "TopClass"): string {
$top_class_name = ucfirst ( $top_class_name );
$classes = array (); // deduplicated 'definition'=>true,array_keys();
$internal = function (array $arr, string $top_class_name) use (&$classes, &$internal) {
$curr = 'Class ' . $top_class_name . ' {' . "\n";
foreach ( $arr as $key => $val ) {
$type = gettype ( $val );
if (is_array ( $val )) {
$type = ucfirst ( ( string ) $key );
$classes [$internal ( $val, ( string ) $key )] = true;
}
$curr .= <<<FOO
/**
* #property $type \$$key
*/
FOO;
$curr .= "\n public $" . $key . ";\n";
}
$curr .= '}';
$classes [$curr] = true;
};
$internal ( $arr, $top_class_name );
return implode ( "\n", array_keys ( $classes ) );
}
output:
Class project {
/**
* #property string $name
*/
public $name;
/**
* #property string $description
*/
public $description;
/**
* #property string $web_url
*/
public $web_url;
/**
* #property NULL $avatar_url
*/
public $avatar_url;
/**
* #property string $git_ssh_url
*/
public $git_ssh_url;
/**
* #property string $git_http_url
*/
public $git_http_url;
/**
* #property string $namespace
*/
public $namespace;
/**
* #property integer $visibility_level
*/
public $visibility_level;
/**
* #property string $path_with_namespace
*/
public $path_with_namespace;
/**
* #property string $default_branch
*/
public $default_branch;
/**
* #property string $homepage
*/
public $homepage;
/**
* #property string $url
*/
public $url;
/**
* #property string $ssh_url
*/
public $ssh_url;
/**
* #property string $http_url
*/
public $http_url;
}
Class author {
/**
* #property string $name
*/
public $name;
/**
* #property string $email
*/
public $email;
}
Class added {
}
Class modified {
/**
* #property string $0
*/
public $0;
}
Class removed {
}
Class 0 {
/**
* #property string $id
*/
public $id;
/**
* #property string $message
*/
public $message;
/**
* #property string $timestamp
*/
public $timestamp;
/**
* #property string $url
*/
public $url;
/**
* #property Author $author
*/
public $author;
/**
* #property Added $added
*/
public $added;
/**
* #property Modified $modified
*/
public $modified;
/**
* #property Removed $removed
*/
public $removed;
}
Class commits {
/**
* #property 0 $0
*/
public $0;
}
Class repository {
/**
* #property string $name
*/
public $name;
/**
* #property string $url
*/
public $url;
/**
* #property string $description
*/
public $description;
/**
* #property string $homepage
*/
public $homepage;
/**
* #property string $git_http_url
*/
public $git_http_url;
/**
* #property string $git_ssh_url
*/
public $git_ssh_url;
/**
* #property integer $visibility_level
*/
public $visibility_level;
}
Class TopClass {
/**
* #property string $object_kind
*/
public $object_kind;
/**
* #property string $event_name
*/
public $event_name;
/**
* #property string $before
*/
public $before;
/**
* #property string $after
*/
public $after;
/**
* #property string $ref
*/
public $ref;
/**
* #property string $checkout_sha
*/
public $checkout_sha;
/**
* #property NULL $message
*/
public $message;
/**
* #property integer $user_id
*/
public $user_id;
/**
* #property string $user_name
*/
public $user_name;
/**
* #property string $user_email
*/
public $user_email;
/**
* #property string $user_avatar
*/
public $user_avatar;
/**
* #property integer $project_id
*/
public $project_id;
/**
* #property Project $project
*/
public $project;
/**
* #property Commits $commits
*/
public $commits;
/**
* #property integer $total_commits_count
*/
public $total_commits_count;
/**
* #property Repository $repository
*/
public $repository;
}
Here's another solution using PDOStatement::fetchObject, though it is a bit of a hack.
$array = array('property1' => 'value1', 'property2' => 'value2');
$className = 'MyClass';
$pdo = new PDO('sqlite::memory:'); // we don't actually need sqlite; any PDO connection will do
$select = 'SELECT ? AS property1, ? AS property2'; // this could also be built from the array keys
$statement = $pdo->prepare($select);
// this last part can also be re-used in a loop
$statement->execute(array_values($array));
$myObject = $statement->fetchObject($className);
Define a static method to convert get an instance from an array. Best, define an interface for it. This is declarative, does not pollute the constructor, allows you to set private properties and still implement custom logic that would not be possible with Reflection. If you want a generic solution, define a trait and use it in your classes.
class Test implements ContructableFromArray {
private $property;
public static function fromArray(array $array) {
$instance = new self();
$instance->property = $array['property'];
return $instance;
}
}
interface ConstructableFromArray {
public static function fromArray(array $array);
}
If you want to cast nested array to object use this code:
class ToObject
{
private $_data;
public function __construct(array $data)
{
$this->setData($data);
}
/**
* #return array
*/
public function getData()
{
return $this->_data;
}
/**
* #param array $data
*/
public function setData(array $data)
{
$this->_data = $data;
return $this;
}
public function __call($property, $args)
{
// NOTE: change lcfirst if you need (ucfirst/...) or put all together
$property = lcfirst(str_replace('get', '', $property));
if (array_key_exists($property, $this->_data)) {
if (is_array($this->_data[$property])) {
return new self($this->_data[$property]);
}
return $this->_data[$property];
}
return null;
}
}
Then you can use like this:
$array = [
'first' => '1.1',
'second' => [
'first' => '2.1',
'second' => '2.2',
'third' => [
'first' => '2.3.1'
]
]
];
$object = new ToObject($array);
$object->getFirst(); // returns 1.1
$object->getSecond()->getFirst(); // returns 2.1
$object->getSecond()->getData(); // returns second array
$object->getSecond()->getThird()->getFirst(); // returns 2.3.1
Just use the php spread operator
class Whatever
{
public function __construct(public int $something) {}
public static function fromArray(array $data)
{
return new self(...$data);
}
}
$data = ['something' => 1];
$instance = Whatever::fromArray($data);
$instance->something; // equals 1
Related
I was trying to get <groupId> tag inside of <workerGroup> tag like so
<ns2:workerGroup>
<ns2:groupId>288</ns2:groupId>
<ns2:groupId>6</ns2:groupId>
<ns2:groupId>125</ns2:groupId>
<ns2:groupId>106</ns2:groupId>
<ns2:groupId>155</ns2:groupId>
</ns2:workerGroup>
but instead I'm getting this
<workerGroup>
<xsd:int>1</xsd:int>
<xsd:int>1</xsd:int>
</workerGroup>
In my opinion the reason behind this logic error is array
While creating Worker object I'm giving an array as an argument
public static function getWorker()
{
$operatorB2b = Role::where('group', 'operator')->first()->users;
$operatorB2c = Role::where('group', 'operator')->orderBy('id', 'DESC')->first()->users;
$merged = $operatorB2b->merge($operatorB2c);
$workers = [];
foreach ($merged as $worker) {
$workers[] = new Worker($worker->id, $worker->first_name, $worker->surname ? $worker->surname : '', '', 1, [1, 1], 1);
}
$main = new Main(
new Personnel(
new Service(
'System', 'System', 1, [1,1]
), $workers
)
);
return $main;
}
Worker Class
<?php
namespace App\Soap\Types;
class Worker
{
/**
* #var int
*/
public $workerId = 1;
/**
* #var string
*/
public $name;
/**
* #var string
*/
public $surname;
/**
* #var string
*/
public $secondName;
/**
* #var int
*/
public $workerStatus = 1;
/**
* #var array
*/
public $workerGroup;
/**
* #var string
*/
public $workerNumber;
/**
* Product constructor.
*/
public function __construct($id, $name = '', $surname = '', $secondName = '', $workerStatus, $workerGroup, $workerNumber = '')
{
$this->workerId = $id;
$this->name = $name;
$this->surname = $surname;
$this->secondName = $secondName;
$this->workerStatus = $workerStatus;
$this->workerGroup = $workerGroup;
$this->workerNumber = $workerNumber;
}
}
Does anyone knows how to solve this issue
Package link:
https://github.com/viewflex/zoap
I am working on a Symfony application. This application uses the Symfony Serializer to deserialize XML objects. These XML objects contain (self-closing) empty elements.
Let's define a minimal model of the object in PHP:
<?php
namespace App\Model;
class PhpObject
{
/**
* #var string
*/
private $required;
/**
* #var null|string
*/
private $optional;
/**
* #return string
*/
public function getRequired(): string
{
return $this->required;
}
/**
* #param string $required
*/
public function setRequired(string $required): void
{
$this->required = $required;
}
/**
* #return string|null
*/
public function getOptional(): ?string
{
return $this->optional;
}
/**
* #param string|null $optional
*/
public function setOptional(?string $optional): void
{
$this->optional = $optional;
}
}
I autowired the serializer using the constructor and then deserialize some XML:
$xml = '
<phpobject>
<required>foo</required>
<optional/>
</phpobject>
';
$result = $this->serializer->deserialize(
$xml,
PhpObject::class,
XmlEncoder::FORMAT,
);
The resulting object $result has now two values:
required = "foo"
optional = ""
How can I achieve that the optional value is null instead of ""?
Don't know the best practice for it, but you can try this.
Change setOptional function to this
/**
* #param string|null $optional
*/
public function setOptional(?string $optional): void
{
$this->optional = $optional === '' ? null : $optional;
}
I'm creating a small API, mostly for learning purposes, but, I might implement it into a project I'm working on. So far, I have installed the zend expressive skeleton application and set up my models and entities. I'm able to query the database and get results, but, when I return the results as a JSON Response, I can only see a list of empty arrays for each result. I would like to be able to return the actual objects that are being returned from the database instead of converting them to arrays.
HomePageHandler.php
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Entity\Product;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router;
use Zend\Expressive\Template\TemplateRendererInterface;
use App\Model\ProductModel;
class HomePageHandler implements RequestHandlerInterface
{
/** #var string */
private $containerName;
/** #var Router\RouterInterface */
private $router;
/** #var null|TemplateRendererInterface */
private $template;
private $productModel;
public function __construct(
string $containerName,
Router\RouterInterface $router,
?TemplateRendererInterface $template = null,
ProductModel $productModel
) {
$this->containerName = $containerName;
$this->router = $router;
$this->template = $template;
$this->productModel = $productModel;
}
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$data = $this->productModel->fetchAllProducts();
return new JsonResponse([$data]);
//return new HtmlResponse($this->template->render('app::home-page', $data));
}
}
I'm expecting a JSON Response returned with a list of 18 "Product" entities. My results look like.
[[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]
Let me know if there is any other code you would like to see.
Thanks in advance!
Edited with Product.php code
<?php
/**
* Created by PhpStorm.
* User: Brock H. Caldwell
* Date: 3/14/2019
* Time: 4:04 PM
*/
namespace App\Entity;
class Product
{
protected $id;
protected $picture;
protected $shortDescription;
protected $longDescription;
protected $dimensions;
protected $price;
protected $sold;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return mixed
*/
public function getPicture()
{
return $this->picture;
}
/**
* #param mixed $picture
*/
public function setPicture($picture)
{
$this->picture = $picture;
}
/**
* #return mixed
*/
public function getShortDescription()
{
return $this->shortDescription;
}
/**
* #param mixed $shortDescription
*/
public function setShortDescription($shortDescription)
{
$this->shortDescription = $shortDescription;
}
/**
* #return mixed
*/
public function getLongDescription()
{
return $this->longDescription;
}
/**
* #param mixed $longDescription
*/
public function setLongDescription($longDescription)
{
$this->longDescription = $longDescription;
}
/**
* #return mixed
*/
public function getDimensions()
{
return $this->dimensions;
}
/**
* #param mixed $dimensions
*/
public function setDimensions($dimensions)
{
$this->dimensions = $dimensions;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getSold()
{
return $this->sold;
}
/**
* #param mixed $sold
*/
public function setSold($sold)
{
$this->sold = $sold;
}
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->picture = (!empty($data['picture'])) ? $data['picture'] : null;
$this->shortDescription = (!empty($data['shortDescription'])) ? $data['shortDescription'] : null;
$this->longDescription = (!empty($data['longDescription'])) ? $data['longDescription'] : null;
$this->dimensions = (!empty($data['dimensions'])) ? $data['dimensions'] : null;
$this->price = (!empty($data['price'])) ? $data['price'] : null;
$this->sold = (!empty($data['sold'])) ? $data['sold'] : null;
}
}
You need to either make the properties public, or implement the JsonSerializable interface in your Product entity. All of its properties are protected, which is fine, but that means they aren't exposed when the object is JSON encoded.
Here are some brief examples:
class Example1 { protected $a = 1; }
class Example2 { public $b = 2; }
class Example3 implements JsonSerializable {
protected $c = 3;
public function jsonSerialize() {
return ['c' => $this->c];
}
}
echo json_encode([new Example1, new Example2, new Example3]);
The result:
[{},{"b":2},{"c":3}]
If you choose to implement JsonSerializable, exactly how you do it is up to you, but you just need a jsonSerialize() method that returns the properties you want in the JSON result in a format accessible to json_encode (an object with public properties or an array).
I want to validate the object properties. Because we do not know PHP OOP more, we chose this way:
First create Validator:
namespace Validator;
/**
* Class ObjectPropertyValidator - Validate object, test if have all property
* #package Validator
*/
class ObjectPropertyValidator {
/**
* #param object $object
*
* #throws ValidatorException
*/
public static function validate($object) {
$reflectionClass = new \ReflectionClass(get_called_class());
foreach ($reflectionClass->getProperties() as $property) {
$name = $property->name;
if (!property_exists($object, $name)) {
throw new ValidatorException('Object not have property ' . $name, 0);
}
new PropertyValidator($property->getDocComment(), $object->$name, $name);
}
}
}
Next I am create Property Validator (I do not have all types validating):
namespace Validator;
/**
* Class PropertyValidator - Parse PHPDOC to pieces and validate input property
* #package Validator
*/
class PropertyValidator {
const DOC_PATTERN = '/#var\s+(?<object>\\\?)(?<type>[0-9A-Za-z\\\]+)(?<array>\[?\]?)/';
const DOC_IS_ARRAY = '[]';
const DOC_IS_OBJECT = '\\';
/** #var bool */
public $is_Array = false;
/** #var bool */
public $is_Object = false;
/** #var string */
public $type = '';
/**
* PropertyValidator constructor.
*
* Where make validating over PHPDOC over $property
*
* #param string $doc PHPDOC
* #param mixed $property Validating Property
* #param string $name Name of property
*/
public function __construct($doc, $property, $name) {
$this->analyzePHPDOC($doc);
$this->validate($property, $name);
}
/**
* #param string $doc
*/
private function analyzePHPDOC($doc) {
if (preg_match(self::DOC_PATTERN, $doc, $matches)) {
$this->is_Array = $matches['array'] === self::DOC_IS_ARRAY;
$this->type = $matches['object'] . $matches['type'];
$this->is_Object = $matches['object'] === self::DOC_IS_OBJECT;
}
}
/**
* #param object $property
* #param string $name
*
* #throws ValidatorException
*/
private function validate($property, $name) {
if ($this->is_Array) {
if (!is_array($property)) {
throw new ValidatorException('Object not have property ' . $name . ' type array', 0);
}
if ($this->is_Object) {
$validator = new $this->type();
foreach ($property as $subobject) {
/** #var ObjectPropertyValidator $validator */
$validator::validate($subobject);
}
}
} else {
if ($this->is_Object) {
$validator = new $this->type();
/** #var ObjectPropertyValidator $validator */
$validator::validate($property);
} else {
switch ($this->type) {
case 'string':
if (!is_string($property)) {
throw new ValidatorException('Property ' . $name . ' is not string', 0);
}
break;
case 'int':
case 'integer':
if (!is_numeric($property)) {
throw new ValidatorException('Property ' . $name . ' is not numeric', 0);
}
break;
}
}
}
}
}
Here I have a skeleton classes for validation (in separate files):
namespace Object;
use Validator\ObjectPropertyValidator;
class SkeletonForValidatingA extends ObjectPropertyValidator {
/** #var string */
public $someProperty;
/** #var \Object\SkeletonForValidatingB[] */
public $somePropertyArray;
}
namespace Object;
use Validator\ObjectPropertyValidator;
class SkeletonForValidatingB extends ObjectPropertyValidator {
/** #var int*/
public $someProperty;
}
And last how to I using all:
$parameters = '{"someProperty":"some text", "somePropertyArray":[{"someProperty":1}]}';
$parameters = Zend_Json::decode($parameters, false);
SkeletonForValidatingA::validate($parameters);
If anyone has any idea how to do it better, please send a tip!
Thank you all
I would like to convert a json into a object / model.
If the json is only one-dimensional, it works perfectly.
But if it is multidimensional, only the outer (user) is converted, but not the inner (company), this remains an array.
Can you help me with this?
The Models:
<?php
namespace AppBundle;
class Company {
/**
* #var string
*/
protected $companyName = '';
/**
* #return string
*/
public function getCompanyName()
{
return $this->companyName;
}
/**
* #param string $companyName
* #return void
*/
public function setCompanyName($companyName)
{
$this->companyName = $companyName;
}
}
class User {
/**
* #var \AppBundle\Company
*/
protected $company = null;
/**
* #var string
*/
protected $username = '';
/**
* #return \AppBundle\Company
*/
public function getCompany() {
return $this->company;
}
/**
* #param \AppBundle\Company $company
* #return void
*/
public function setCompany($company) {
$this->company = $company;
}
/**
* #return string
*/
public function getUsername() {
return $this->username;
}
/**
* #param string $username
* #return void
*/
public function setUsername($username) {
$this->username = $username;
}
}
?>
Convert json to model:
<?php
namespace AppBundle\Controller;
class DefaultController extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
{
public function indexAction()
{
// Initialize serializer
$objectNormalizer = new \Symfony\Component\Serializer\Normalizer\ObjectNormalizer();
$jsonEncoder = new \Symfony\Component\Serializer\Encoder\JsonEncoder();
$serializer = new \Symfony\Component\Serializer\Serializer([$objectNormalizer], [$jsonEncoder]);
// Set test model
$company = new \AppBundle\Company();
$company->setCompanyName('MyCompany');
$user = new \AppBundle\User();
$user->setCompany($company);
$user->setUsername('MyUsername');
// Serialize test model to json
$json = $serializer->serialize($user, 'json');
dump($user); // Model ok, Company is instance of \AppBundle\Company
dump($json); // json ok + valide
// Deserialize json to model
$user = $serializer->deserialize($json, \AppBundle\User::class, 'json');
dump($user); // Error: Company is now array instead instance of \AppBundle\Company
// Denormalize json to model
$userArray = $serializer->decode($json, 'json');
$user = $serializer->denormalize($userArray, \AppBundle\User::class);
dump($user); // Error: Company is now array instead instance of \AppBundle\Company
}
}
?>
I solved the problem.
On the one hand you need PHP 7. Annotations I have not yet tested.
Then the variable has to be set correctly in setCompany().
public function setCompany(Company $company) {
$this->company = $company;
}
And the ReflectionExtractor() must be used.
use Symfony\Component\Serializer\Normalizer;
use Symfony\Component\PropertyInfo\Extractor;
$objectNormalizer = new ObjectNormalizer(
null,
null,
null,
new ReflectionExtractor()
);
You only need deserialize(), because it decode() and denormalize().
http://symfony.com/doc/current/components/serializer.html
Full fixed code:
Company class:
class Company {
/**
* #var string
*/
protected $companyName = '';
/**
* #return string
*/
public function getCompanyName() {
return $this->companyName;
}
/**
* #param string $companyName
* #return void
*/
public function setCompanyName($companyName) {
$this->companyName = $companyName;
}
}
User class:
class User {
/**
* #var \AppBundle\Company
*/
protected $company = null;
/**
* #var string
*/
protected $username = '';
/**
* #return \AppBundle\Company
*/
public function getCompany() {
return $this->company;
}
/**
* #param \AppBundle\Company $company
* #return void
*/
public function setCompany(Company $company) {
$this->company = $company;
}
/**
* #return string
*/
public function getUsername() {
return $this->username;
}
/**
* #param string $username
* #return void
*/
public function setUsername($username) {
$this->username = $username;
}
}
?>
Controller class:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\Serializer\Normalizer;
use Symfony\Component\PropertyInfo\Extractor;
use Symfony\Component\Serializer;
class DefaultController extends Controller {
public function indexAction() {
$objectNormalizer = new ObjectNormalizer(
null,
null,
null,
new ReflectionExtractor()
);
$jsonEncoder = new JsonEncoder();
$serializer = new Serializer([$objectNormalizer], [$jsonEncoder]);
$company = new \AppBundle\Company();
$company->setCompanyName('MyCompany');
$user = new \AppBundle\User();
$user->setCompany($company);
$user->setUsername('MyUsername');
$json = $serializer->serialize($user, 'json');
dump($user, $json);
$user2 = $serializer->deserialize($json, \AppBundle\User::class, 'json');
dump($user2);
}
}
?>