Posts

Showing posts from November, 2012

Zend Framework 2 model database adapter depedency injection

Typically most of the model classes depend on database adapter. First way to get database adapter instance is to request it via service manager every time you need it. Second, and more convenient one, is to let Zend\Di do all the magic for you. To achieve this you need to implement Zend\Db\Adapter\AdapterAwareInterface in your model class. Or write an abstract class that implements this interface and extend it with your model class and Zend\Di will inject database adapter dependency. Note: to make this work you should instantiate model classes via ServiceManager . How to setup a database adapter is explained in Getting Started with Zend Framework 2 . Abstract class example: <?php //module/<YOUR_MODULE>/src/<YOUR_MODULE>/Model/AbstractAdapterAware.php namespace <YOUR_MODULE>\Model; use Zend\Db\Adapter\Adapter; use Zend\Db\Adapter\AdapterAwareInterface; abstract class AbstractAdapterAware implements AdapterAwareInterface { /** * Database instan...

Zend Framework 2 AJAX: return JSON response from controller action. The proper way.

There is a lot of solutions over the web on how to return data on AJAX request in your Zend Framework 2 application. But none of them seems to be aware of the "right way" described in Zend Framework 2 manual - http://framework.zend.com/manual/2.0/en/modules/zend.mvc.examples.html#returning-early Implementation example: <?php namespace <YOUR_MODULE>\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\Json\Json; class AjaxController extends AbstractActionController { public function testAction() { $data = array( 'result' => true, 'data' => array() ) return $this->getResponse()->setContent(Json::encode($data)); } }

Zend Framework 2 navigation menu to array dehydration view helper

Sometimes you need to customize Zend Framework navigation menu output. For instance change <ul><li> output to <div><span>. This is impossible with Zend\View\Helper\Navigation\Menu because its HTML output isn't much customizable (only things like class, indent etc.). Such customization is possible with "partial" script, but my solution is to write a view helper that utilizes navigation menu to array dehydration. Helper: <?php //<YOUR_MODULE>/View/Helper/NavigationMenuDehydrate.php namespace <YOUR_MODULE>\View\Helper; use Zend\View\Helper\AbstractHelper; use RecursiveIteratorIterator; class NavigationMenuDehydrate extends AbstractHelper { protected $container; public function __invoke($container = null) { $this->container = $container; return $this; } public function dehydrate() { $array = array(); $iterator = new RecursiveIteratorIterator($this->getVie...