Я создаю приложение, в котором мне нужны все действия фреймворка для вывода данных в виде XML.
Как этого добиться?
Я создаю приложение, в котором мне нужны все действия фреймворка для вывода данных в виде XML.
Как этого добиться?
Есть несколько способов добиться этого:
1 Реализовать событие afterExecuteRoute
class MyController extends Phalcon\Mvc\Controller
{
public function showAsXml1Action()
{
return "<root><key>k</key></root";
}
public function showAsXml2Action()
{
return "<root><key>k</key></root";
}
public function afterExecuteRoute($dispatcher)
{
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($dispatcher->getReturnedValue());
$dispatcher->setReturnedValue($response);
}
}
2 Создайте класс, который обрабатывает ответы XML:
class MyXMLResponse extends Phalcon\Http\Response
{
public function __construct($xml)
{
$this->setHeader('Content-Type', 'application/xml');
$this->setContent($xml);
}
}
в контроллере:
public function showAsXml2Action()
{
return MyXmlResponse("<root><key>k</key></root");
}
3 Создайте подключаемый модуль, который обрабатывает ответы XML:
class MyController extends Phalcon\Mvc\Controller
{
public function showAsXml1Action()
{
return array(
"type" => "xml",
"content" => "<root><key>k</key></root",
);
}
}
Плагин:
class ContentTypePlugin extends \Phalcon\Mvc\User\Plugin
{
public function afterExecuteRoute($event, $dispatcher)
{
$content = $dispatcher->getReturnedValue();
switch ($content['type']) {
case 'xml':
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($content['content']);
$dispatcher->setReturnedValue($response);
break;
}
}
}
Использование аннотаций
/**
* @Response(type="xml")
*/
public function showAction()
{
return "<root><key>k</key></root";
}
Плагин:
class AnnotationsContentPlugin extends \Phalcon\Mvc\User\Plugin
{
public function afterExecuteRoute($event, $dispatcher)
{
$annotations = $this->annotations->getMethod(
$dispatcher->getActiveController(),
$dispatcher->getActiveMethod()
);
// Check if the method has an annotation 'Response'
if ($annotations->has('Response')) {
// Get the type
$type = $annotations->get('Response')
->getNamedParameter('type');
if ($type == 'xml') {
$response = new Phalcon\Http\Response();
$response->setHeader('Content-Type', 'application/xml');
$response->setContent($dispatcher->getReturnedValue());
$dispatcher->setReturnedValue($response);
}
}
}
}
Если вам нужно использовать иерархию файлов для вывода XML, например:
app/views/index.phtml
app/views/layouts/posts.phtml
app/views/posts/show.phtml
вы можете использовать следующий код в действии
public function showAction()
{
$this->view->setRenderLevel(Phalcon\Mvc\View::LEVEL_ACTION_VIEW);
$this->view->xml = '<root><key>k</key></root>';
}
и в представлении:
<?php echo $xml; ?>