I've worked on this code base and it responds with html when i access a site www.site.com/version/
However, If i access www.site.com/version?format=xml, it displays output in xml.
How can I change the Zend code to ONLY output in XML irrespective of the format request? Yeah, i'm new to Zend coding...)
My code is exactly what Chris has ( http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/ ) :
class VersionController extends Zend_Rest_Controller
{
public function init()
{
$bootstrap = $this->getInvokeArg('bootstrap');
$options = $bootstrap->getOption('resources');
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('index', array('xml','json'))->initContext();
//$this->_helper->viewRenderer->setNeverRender();
$this->view->success = "true";
$this->view->version = "1.0";
}
...
...
You can force the context to use XML only by following code:
$this->_helper->contextSwitch()->initContext('xml');
Refer link:
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch.initcontext
Related
I try to implement a webservice Client using php and got stuck...
I'm using an existing webservice called metadataservice with a known wsdl.
I'll use wsdl2phpgenerator to create the php classes for the datatypes and the Service itself.
Using one of the Webservice Methods (addMetadataToObject), I have to send an Array of objects to the Server.
There is a base class:
class AssetInfo
{
public $dataFieldId = null;
public $dataFieldName = null;
public $dataFieldTagName = null;
public function __construct($dataFieldId, $dataFieldName, $dataFieldTagName)
{
$this->dataFieldId = $dataFieldId;
$this->dataFieldName = $dataFieldName;
$this->dataFieldTagName = $dataFieldTagName;
}
}
and a derived class Holding string values (there are also other derived classes for Longs etc.):
class StringAssetInfo extends AssetInfo
{
public $value = null;
public function __construct($dataFieldId, $dataFieldName,$dataFieldTagName, $value)
{
parent::__construct($dataFieldId, $dataFieldName, $dataFieldTagName);
$this->value = $value;
}
}
For the call of Metadataservice->addMetadataToObject there is also a addMetadataToObject defined:
class addMetadataToObject
{
public $objectId = null;
public $objectType = null;
public $assetInfos = null;
public function __construct($objectId, $objectType)
{
$this->objectId = $objectId;
$this->objectType = $objectType;
}
}
The property $assetInfos should hold an Array of AssetInfo objects. wdsl2phpgenerator creates a class for my MetadataService which is derived from SoapClient. This class provides all the avialable Methods for this Service. Here I only show the addMetadataToObject Method:
public function addMetadataToObject(addMetadataToObject $parameters)
{
return $this->__soapCall('addMetadataToObject', array($parameters));
}
My Code does:
// Define the Data
$ServiceOptions = [];
$AssetInfos = [];
$AssetInfo = new StringAssetInfo(2, "TitleName", "TitleName","New Title Name);
array_push($AssetInfos, $AssetInfo);
// Create the Service
$Service = new MetadataService($ServiceOptions, getServiceWSDL($Options, "MetadataService"));
$Service->__setSoapHeaders(getGalaxySoapHeader($Options));
$NewMetaData = new addMetadataToObject(61755, "ASSET");
$NewMetaData->assetInfos = $AssetInfos;
// Call the Service
$failedAssets = $Service->addMetadataToObject($NewMetaData);
The call throws a Soap Exception that a value could not be extracted. Which makes me wonder. I started to monitor the traffic to the Soap Server using wireshark and yes....there is no value anymore as defined in the StringAsset Info Class...Here is the Soap Body shown by wireshark:
<SOAP-ENV:Body>
<ns1:addMetadataToObject>
<objectId>61755</objectId>
<objectType>ASSET</objectType>
<assetInfos>
<dataFieldId>2</dataFieldId>
<dataFieldName>TitleName</dataFieldName>
<dataFieldTagName>TitleName</dataFieldTagName>
</assetInfos>
</ns1:addMetadataToObject>
Id</SOAP-ENV:Body>
I would expect a tag New Title Name. But ist gone. When I checked the $NewMetaData object in my Code or the $Parameter object in $Service->addMetadataToObject I can see that the property "Value" is defined and set.
For me it seems, that the call to
return $this->__soapCall('addMetadataToObject', array($parameters));
only accepts the properties of the base class AssetInfo but not the properties from the derived class StringAssetInfo.
I also changed the Code to use an Array (instead of an object) for $AssetInfo:
$AssetInfo = array("dataFieldId"=>2, "dataFieldName"=>"TitleName","dataFieldTagName"=>"TitleName, "value"=>"New Title Name");
But without any change. It seems that we have here some Kind of runtime type conversion or type alignment but I can't see the reason of this. I'm still new to webservices at all and also on php (however I have to use both for the Moment:-)
Can anybody comment or give me a hint what's happening here?
I was able to realize it by using Arrays and soapvars, Please note my comments in the code:
$ServiceOptions = [];
$AssetInfos = [];
// I have to use an Array because the Server depends on the order of the properties. I wasn't able to define expected order using the existing objects but with arrays
$AssetInfo = array("dataFieldId"=>2, "dataFieldName"=>"TitleName","dataFieldTagName"=>"TitleName, "value"=>"New Title Name");
// instead of pushing the Array directly, I create an instance of an SoapVar, pass the Array as data and set the Encoding, the expected type and the Namespace uri
array_push($AssetInfos, new SoapVar($AssetInfo, SOAP_ENC_OBJECT, "StringAssetInfo", "http://metadataservice.services.provider.com"));
array_push($AssetInfos, $AssetInfo);
// Create the Service
$Service = new MetadataService($ServiceOptions, getServiceWSDL($Options, "MetadataService"));
$Service->__setSoapHeaders(getGalaxySoapHeader($Options));
$NewMetaData = new addMetadataToObject(61755, "ASSET");
$NewMetaData->assetInfos = $AssetInfos;
// Call the Service
$failedAssets = $Service->addMetadataToObject($NewMetaData);
This produced the expected Output in the Soap Body (and also added some namespaces to the Soap envelope
<SOAP-ENV:Body>
<ns1:addMetadataToObject>
<objectId>61755</objectId>
<objectType>ASSET</objectType>
<assetInfos xsi:type="ns1:StringAssetInfo">
<dataFieldId>2</dataFieldId>
<dataFieldName>TitleName</dataFieldName>
<dataFieldTagName>TitleName</dataFieldTagName>
<value>New Titel Name 1146</value>
</assetInfos>
</ns1:addMetadataToObject>
</SOAP-ENV:Body>
I have been successfully using XML view files in CakePHP (request the XML output type in headers so CakePHP will use e.g. Orders/xml/create.ctp instead of Order/create.ctp).
However, now i need to add some functionality that requires me to the reformat the XML at the end of most business logic in the controller.
So i tried this in the controller action:
public function createorder() {
$this->autoRender = false; // disable automatic content output
$view = new View($this, false); // setup a new view
{ ... all kinds of controller logic ...}
{ ... usually i would be done here and the XML would be outputted, but the autorender will stop that from happening ... }
{ ... now i want the XML in a string so i can manipulate the xml ... }
$view_output = $view->render('createorder'); // something like this
}
But what this gives me is:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<error>View file "/Users/test/Documents/hosts/mycakeapp/app/View/Orders/createorder.ctp" is missing.</error>
<name>MissingViewException</name>
<code>500</code>
<url>/orders/createorder/</url>
</response>
So i need to tell CakePHP to pickup the xml/createorder.ctp instead of createorder.ctp. How do i do this?
Cheers!
This answers refers to cakephp 2.4
I have been successfully using XML view files in CakePHP (request the XML output
type in headers so CakePHP will use e.g. Orders/xml/create.ctp
instead of Order/create.ctp).
In lib/Cake/View you can see different View files like:
View.php
XmlView.php //This extends View.php
JsonView.php //This extends View.php
So you told cakephp to use the XmlView. When you create a new View you need to use the XmlView instead of View. Or you can create your own custom View and put it inside app/View folder. In your custom View you can set your subdir.
<?php
App::uses('View', 'View');
class CustomView extends View {
public $subDir = 'xml';
public function __construct(Controller $controller = null) {
parent::__construct($controller);
}
public function render($view = null, $layout = null) {
return parent::render($view, $layout);
}
}
So what you need now is to create your custom view $view = new CustomView($this, false);
You can also write in your CustomView functions to handle the data as xml and use it to every action.
Also #Jelle Keizer answer should work. $this->render('/xml/createorder'); points to app/View/xml/createorder. If you need this to point to app/View/Order/xml/create just use $this->render('/Orders/xml/create');.
$this->render('/xml/createorder');
SOLVED Thanks to #JPR and tuned-up thanks to #PeterM
/* The only dependance is when */ class NuSoap extends CApplicationComponent
v-Below, the initial question -v
I would like to know how to create a basic extenstion in yii 1.1.13 using nusoap 0.9.5?
My simple code looks like this :
<?php
require("libs/nusoap-0.9.5/lib/nusoap.php");
// namespace
$ns = "https://my-namespace-site";
// client
$client = new soapclient('https://ip-to-webservice-server');
// header
$headers = "<credentials><ns1:username xmlns:ns1=\"$ns\">username</ns1:username>
<ns2:password xmlns:ns2=\"$ns\">password</ns2:password></credentials>";
$client->setHeaders($headers);
// searching
$params = array(
'local_user_array' => array(
'limit' => 10
)
);
$result = $client->call('local_users_search', $params, $ns );
if( $client->getError() ) {
echo $client->getError();
}
else {
foreach( $result['data'] as $offer ) {
echo "<div>".$offer['firstname']."</div>";
}
}
?>
My code works perfectly. Now, what coud I do to use $result in yii to be able to show results in a view?
The best answer will be a concrete example with file structure and code plus meaningful explanations.
Any help would be greatly appreciated. Thanks for your help in advance. I'm looking forward to it ;-)
PS: please do not reference any links to yiiframework site because it doesn't help much as I also know how to search.
Make a class that extends from CApplicationComponent.
class NuSoap extends CApplicationComponent
{
protected $params = array();
protected $client, $ns;
public function init() {
require("libs/nusoap-0.9.5/lib/nusoap.php");
$this->client = new soapclient('https://ip-to-webservice-server');
$this->ns = "https://my-namespace-site";
}
public function getResults() {
$results = $this->client->call(
'local_users_search',
$this->params,
$this->ns
);
return $results;
}
public function setParams(array $params) {
$this->params = $params;
}
// whatever other methods you need for it to work
}
Then in your main config file, under the components array:
array(
'nuSoap' => array(
'class' => 'application.components.NuSoap' // name your class NuSoap.php
)
......
)
Make sure the application/components or application/extensions directory is imported in the main.php config file as well. Put your class file in NuSoap.php in the application/components or applcation/extensions directory.
You can now refer to your component anywhere in your Yii app:
Yii::app()->nuSoap->setParams($params);
$results = Yii::app()->nuSoap->getResults();
This should be plenty to get you started in the right direction. The Yii documentation would be very helpful in understanding how application components work, but since you don't want to read it you'll just have to guess on some things. If you want to use Yii it makes absolutely no sense to avoid reading the documentation.
I've a php class and i want to use it with Nusoap. Can I register the class method's that already exists inside the nusoap with the register command?
Sample :
Here we register a function that we defined inside this script. But if we've a class that we maybe develop months ago and we want to use it as a webservice using the WSDL. Is there a way to register the methods of that class so that Nusoap creates a WSDL of it's stucture (methods inside)?
require_once("nuSOAP/lib/nusoap.php");
$server = new soap_server();
$namespace = "http://localhost/nusoapSCRIPT/index.php";
$server->wsdl->schemaTargetNamespace = $namespace;
$server->configureWSDL("SAMPLE");
$server->register('HelloWorld');
function HelloWorld()
{
return "Hello, World!";
}
Well here's how i solve this... maybe someone can try an approach in another way.
[File : index.php]
require_once "nuSOAP/lib/nusoap.php";
require_once "myClass.class.inc.php";
$namespace = "http://localhost/html/nusoap/index.php";
// create a new soap server
$server = new soap_server();
// configure our WSDL
$server->configureWSDL("Class Example");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
// register the class method and the params of the method
$server->register("myClass.ShowString"
,array('name'=>'xsd:string')
,array('return'=>'xsd:string')
,$namespace,false
,'rpc'
,'encoded'
,'Sample of embedded classes...'
);
//
// Get our posted data if the service is being consumed
// otherwise leave this data blank.
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])
? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
exit();
and the class code.
[File 'myClass.class.inc.php']
class myClass{
public function __construct(){
}
public function ShowString($mens){
return "\n##Remote Class :".__CLASS__."\n##Remote Method : ".__METHOD__."\n## mSG :{$mens}";
}
}
I also create a soap client in c# and it consumes correctly the soap service.
Hope this help!
You can call the method using getProxy()
$proxy->className__methodname
I am trying to use AMF PHP to pass variables to a flash file, thus far I cannot see anything wrong with my code, but I have very little experience with creating classes, so here it goes, here is my code,
index.php:
<?php
include "amfphp/services/flashMe.php";
$session = true;
if ($session == true) {
$uid = '12345';
$thing = new flashMe;
$thing->push($uid);
} else {
//login
}
?>
flashMe.php:
<?php
class flashMe {
public function __construct() {
}
public function push($one)
{
return $one;//sends the uid to the flash file?
}
}
?>
Flash is looking for the flashMe class and the push method within that class, but I keep getting null variables in my flash file when I run it, is there something wrong with this code?
Thanx in advance!
Your index.php file is unnecessary.
Your second file is incomplete. Here is the example from the docs for their "hello world" class file:
<?php
class HelloWorld
{
function HelloWorld()
{
$this->methodTable = array
(
"say" => array
(
"access" => "remote",
"description" => "Pings back a message"
)
);
}
function say($sMessage)
{
return 'You said: ' . $sMessage;
}
}
?>
This file should be saved as "HelloWorld" matching the "class HelloWorld" you have named in the php file (you did this part right with FlashMe).
The example file in the docs for the Flash piece (in actionscript) is here:
import mx.remoting.*;
import mx.rpc.*;
import mx.remoting.debug.NetDebug;
var gatewayUrl:String = "http://localhost/flashservices/gateway.php"
NetDebug.initialize();
var _service:Service = new Service(gatewayUrl, null, 'HelloWorld', null , null);
var pc:PendingCall = _service.say("Hello world!");
pc.responder = new RelayResponder(this, "handleResult", "handleError");
function handleResult(re:ResultEvent)
{
trace('The result is: ' + re.result);
}
function handleError(fe:FaultEvent)
{
trace('There has been an error');
}
The gateway URL should go to wherever your services can be reached. I'm sure if you try a few you'll find the right one. The neat thing about amfphp is that it allows you to also test your services out before you try implementing them in the gateway (if you go to the URL in your browser).
I'm pretty new to AMFPHP as well, but I've found the docs to be extraordinarily useful. If you need more help on classes, you can find more info on the PHP docs page.
You missed the parenthesis after new flashMe
$thing = new flashMe();
$thing->push($uid);
Amfphp or Zend AMF only allow you to call public methods on a remote class that is exposed by your gateway. You example is not a class and therefore no remote method can be called. This looks more like something that you would do with an http post.
http://framework.zend.com/manual/en/zend.amf.server.html