ContextSwitch action helper example
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 64 6566 67 68 69 7071 72 73 74 7576 77 78 79 8081 82 83 84 85 | ## /application/controllers/EnglandController.php <?php /** * Simple example of using the context switch * * @author Dave Marshall */ class EnglandController extends Zend_Controller_Action { public function init() { $this->_helper->contextSwitch() ->addActionContext('a', array('xml', 'json')) ->setAutoJsonSerialization(true) ->initContext(); } public function aAction() { $this->view->team = 'a'; $this->view->players = array( 'David James', 'Ashley Cole', 'John Terry', 'Rio Ferdinand', 'Glen Johnson', 'Joe Cole', 'Steven Gerrard', 'Frank Lampard', 'David Beckham', 'Wayne Rooney', 'Michael Owen', ); }} ## /application/views/scripts/england/a.xml.phtml <?php echo "<?xml version="1.0" ?>";?> <team><name><?php echo $this->team; ?></name> <players> <?php foreach($this->players as $player):?> <player><?php echo $player; ?></player> <?php endforeach; ?></players> </team> ## http://yourhost/england/a/format/xml would output <?xml version="1.0" ?><team><name>a</name> <players> <player>David James</player> <player>Ashley Cole</player> <player>John Terry</player> <player>Rio Ferdinand</player> <player>Glen Johnson</player> <player>Joe Cole</player> <player>Steven Gerrard</player> <player>Frank Lampard</player> <player>David Beckham</player> <player>Wayne Rooney</player> <player>Michael Owen</player> </players> </team> ## http://yourhost/england/a/format/json would output { "team":"a", "players":[ "David James", "Ashley Cole", "John Terry", "Rio Ferdinand", "Glen Johnson", "Joe Cole", "Steven Gerrard", "Frank Lampard", "David Beckham", "Wayne Rooney", "Michael Owen" ] } |
Comments
How do you change that the main layout to not be disabled on contextSwitch ? Also I think it can't handle properly the call of the action view helper within the view script as this:
<?php echo $this->action("index", "index", "items")?>
Thanks!
You must login before commenting on a snippet. If you do not have an account, please register.
Snippet description
This is a very basic example of using the ContextSwitch action helper
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch
We don't need a view template for the json format, by calling setAutoJsonSerialization with true, the framework will automatically json encode any variables assigned to the view.
Snippet details
- Created:
-
davedevelopment
- Edited:
-
davedevelopment
- Revision Id:
- 78
- Edit Message:
- Fixed url in second example output
- Tags:
- action helper json xml context switch
- Comments:
- 3
- Views:
- 12926
- Points:
- 2 (2 votes)
4 years ago
Second URL should be http://yourhost/england/a/format/json ;)