Press enter to see results or esc to cancel.

Zend Framework 2 Best Practices

1. Resources

2. Ajax and ZF2

How to response in JSON and HTML format in ZF2 Controller ? There is some solution:

Return a response object (disable layout and view)

public function getListAction() 
{
    $contacts = array( 'foo' => 'bar' );
    $response = $this->getResponse();
    $response->getHeaders()->addHeaderLine( 'Content-Type', 'application/json' );
    $response->setContent(json_encode($contacts));
    return $response;
}

Terminate the script

public function getListAction() 
{
    $contacts = array( 'foo' => 'bar' );
    echo json_encode($contacts);
    exit;
}

Return false disables the view and not the layout because the accepted types are: ViewModel, array, null

public function getListAction() 
{
    // code here
    return false;
}

setTerminal(true) to disable layout. Use for Ajax datatype html

public function getListAction() 
{
    $result = new ViewModel(array(
        'data' => $data
    ));
    $result->setTerminal(true);
    return $result;
}

3. ZF2 Security

Cross-Site Scripting (XSS)

Always escape output, ZF2 view helpers provide multiple methods

  • escapeHtml: escape a string for the HTML Body context.
  • escapeHtmlAttr: escape a string for the HTML Attribute context.
  • escapeJs: escape a string for the Javascript context.
  • escapeCss: escape a string for the CSS context.
  • escapeUrl: escape a string for the URI or Parameter contexts.

 

Cross-Site Request Forgery (CSRF)

Using the ZF2 CSRF Form Element to include a hidden field with a unique token per request.

$form = new \Zend\Form\Form\Form('my-form');
$form->add(array(
    'type' => 'Zend\Form\Element\Csrf',
    'name' => 'csrf',
    'options' => array(
            'csrf_options' => array(
                    'timeout' => 600
            )
    )
));

 

4. Integrate Elasticsearch in ZF2

stackoverflow.com

 

Comments

Leave a Comment