ZF2 View Strategy

I am trying to implement the following:

Simple controller and action. The action should return a response of two types depending on the request:

HTML in case of ordinary request (text\html), JSON in case of ajax request (application\json) 

I managed to do this through the plugin for the controller, but it requires writing

 return $this->myCallBackFunction($data) 

in every action. But what if I do not do this for the entire controller? I tried to figure out how to implement it through an event listener, but could not succeed.

Any tips or links to some articles would be appreciated!

+4
source share
1 answer

ZF2 specifically for this purpose has a controller plug-in an acceptable view model selector . It will select the appropriate ViewModel based on the mapping you define by looking at the Accepts header sent by the client.

In your example, you first need to enable the JSON view strategy by adding it to the view manager configuration (usually in module.config.php ):

 'view_manager' => array( 'strategies' => array( 'ViewJsonStrategy' ) ), 

(You probably already have the view_manager switch, in which case add the β€œstrategy” part to your current configuration.)

Then in the controller, you call the controller plugin using your mapping as a parameter:

 class IndexController extends AbstractActionController { protected $acceptMapping = array( 'Zend\View\Model\ViewModel' => array( 'text/html' ), 'Zend\View\Model\JsonModel' => array( 'application/json' ) ); public function indexAction() { $viewModel = $this->acceptableViewModelSelector($this->acceptMapping); return $viewModel; } } 

This will return a normal ViewModel for standard requests and JsonModel for requests that accept a JSON response (i.e. AJAX requests).

Any variables assigned by JsonModel will be displayed in JSON output.

+5
source

Source: https://habr.com/ru/post/1499804/


All Articles