Skip to main content
Image for post: Zend Framework 2 tips and tricks

Zend Framework 2 tips and tricks

Managing Zf2 code

Zend Framework 2 is becoming the most popular PHP framework. I'm using it every day since a couple months and I still have many difficulties to build my own and simple web application. The learning curve is very steep and you have to handle a large amount of code. But it has a large community, strong MVC implementation, large number of libraries ready to use and many other advantages. We have to apply the OOP principles and write unit tests. This will allow us to not loose the control of our code. I've gathered some snippets. I hope they can be useful if you are using this framework. Zend Form: add a select with optgroup:


$this->add(array(
'name'=>'Test',
'type'=>'Zend\Form\Element\Select',
'attributes'=>array('type'=>'select','required'=>'required','class'=>'form-control'),
'options'=>array(
'label'=>'Test',
'value_options'=>array('fruits'=>array('label'=>'Fruits','options'=>array('1'=>'Apple','2'=>'Mango')),'animals'=>array('label'=>'Animals','options'=>array('cat'=>'CAT','dog'=>'DOG'))),
'empty_options'=>'Please Select'
),

));

Check if a controller exists (from another controller):


/**
* Check if controller and action exists
* @param string $controller
* @param string $action
* @return boolean
*/
protected function validateDispatchable($controller, $action)
{
$loader = $this->getServiceLocator()->get('ControllerLoader');
if (!$loader->has($controller)) {
return false;
}

$obj    = $loader->get($controller);
$method = $obj::getMethodFromAction($action);

if (!method_exists($obj, $method)) {
return false;
}

return true;
}

Check if a template exists (this is a good check before render the layout or template):


/**
* Check if template exists
* @param unknown $template
* @return boolean
*/
private function validateTemplate($template)
{
$resolver = $this->getEvent()
->getApplication()
->getServiceManager()
->get('Zend\View\Resolver\TemplatePathStack');

if (false === $resolver->resolve($template)) {
return false;
}
return true;
}

 

Share this post

This website and/or any sub domains use cookies to understand how you to improve your experience.