简体   繁体   中英

How do you send a JSON encoded object to a PHP function that takes a PHP class object as a variable?

I have a java aplet that is sending a JSON encoded object to a Zend Framework JSON Server.

the problem that I have is the code is setup like this:

ServerController:

public function jsonAction()
{

$server = new Zend_Json_Server();
$Server->setClass('Application_Model_ClassObject', 'co');

if('GET' == $_SERVER['REQUEST_METHOD'])
{
    $server->setTarget('...')
           ->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
    $smd = $server->getServiceMap();

    header('Content-Type: application/json');

    echo $smd;
    return
}

echo $server->handle();
}

ClassObject function:

/**
* DoSomethign description
* @param ClassObject
*/
public function doSomething(Application_Model_ClassObject $obj)
{

    $someVariable = $obj->getSomeValue();
    ...
}

I get an error response from the server saying that obj needs to be an instance of ClassObject

Ok so this is what we ended up doing (Quick and dirty version)... Although i believe there is a better way.

  1. Removed the type-hint so that the function will be able to receive any data.
  2. Create a new function in "Application_Model_ClassObject" that will handle an array of data or an object.
  3. Added a few extra lines to "doSomething" so that the rest can go on as normal.

Here are some details:

/**
* DoSomethign description
* @param ClassObject
*/
public function doSomething($data)
{
    $obj = new Application_Model_ClassObject();
    $obj->populate($data);

    $someVariable = $obj->getSomeValue();
    ...
}

/**
*
* Application_Model_ClassObject class
*/
class Application_Model_ClassObject
{
    ...

    public function populate($row)
    {
        if (is_array($row)) {
        $row = new ArrayObject($row, ArrayObject::ARRAY_AS_PROPS);
        }

        if (isset ($row->SomeValue)) {
        $this->setSomeValue($row->SomeValue);
        }

        return $this;
    }

}

如果删除类型提示“ ClassObject”,则doSomething方法将接受任何传入的数据。然后由doSomething方法来解码json字符串,并对其进行一些有用的处理。

public function doSomething(ClassObject obj) { ... }

Um, usually you don't write PHP functions like that, as it's not strongly typed. Normally, it looks like this instead:

public function doSomething($obj) {...}

It looks like you've tried to write a PHP function with some Java syntax mixed in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM