Как улучшить административные контроллеры, используемые для crud - PullRequest
0 голосов
/ 24 августа 2011

Я использую Zend Framework и в моем приложении администратор в основном используется для операций CRUD.Я не использую Zend Form, и я хочу сохранить это, если это возможно, но я думаю, что мой код совсем не хорош, и что его можно улучшить, поэтому я спрашиваю вас, как лучше организовать этот класс(поскольку все мои занятия выглядят одинаково красиво) ...

Вот код:

http://pastie.org/2422147

1 Ответ

1 голос
/ 24 августа 2011

Честно говоря, улучшение состояло бы в использовании Zend_Form.Почему вы не используете Zend_Form?Если вы не можете получить индивидуальный внешний вид, который вам требуется при использовании декораторов, есть способы использовать zend_Form без использования этих вещей.

Sample Admin CRUD Controller (for hierarchical categories) <pre><code>class StoreAdmin_CategoryController extends Zend_Controller_Action { protected $_flashMessenger = null; public function init() { $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger'); $this->initView(); } public function indexAction() { $this->_forward('list'); } public function listAction() { $table_category = new Store_Model_DbTable_Category(); $obj_select = $table_category->build_select(array(), array('order_by' => 'ASC')); $arr_categories = $table_category->fetch_all_objects($obj_select); $table_category = new Store_Model_DbTable_Category(); $hierarchy = $table_category->get_hierarchy(NULL); $this->view->assign('arr_categories', $arr_categories); $this->view->assign('hierarchy', $hierarchy); } public function createAction() { $form = new StoreAdmin_Form_Category(); if($this->getRequest()->isPost()) { if($form->isValid($this->getRequest()->getPost())) { $table_category = new Store_Model_DbTable_Category(); $category = $table_category->get(); $category->set_name($form->getValue('name')); $category->set_slug($form->getValue('slug')); $category->set_description($form->getValue('description')); $category->set_order_by($form->getValue('order_by')); $category->set_id_parent($form->getValue('id_parent')); $category->set_date_created(time()); $category->set_date_modified(time()); $table_category->save($category); $this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully created!", $category->get_name()))); $this->_redirect('/store-admin/category/list'); } else { $this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below")); } } $this->view->assign('form_category', $form); } public function updateAction() { $id_category = $this->getRequest()->getParam('id_category'); if(empty($id_category)) { throw new Zend_Exception('Error: Category ID Missing from request'); } $form = new StoreAdmin_Form_Category(); $form->removeOption($id_category); $table_category = new Store_Model_DbTable_Category(); $category = $table_category->get($id_category); if($this->getRequest()->isPost()) { if($form->isValid($this->getRequest()->getPost())) { $category->set_name($form->getValue('name')); $category->set_slug($form->getValue('slug')); $category->set_description($form->getValue('description')); $category->set_order_by($form->getValue('order_by')); $category->set_id_parent($form->getValue('id_parent') ? $form->getValue('id_parent') : NULL); $category->set_date_modified(time()); $table_category->save($category); $this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully updated!", $category->get_name()))); $this->_redirect('/store-admin/category/list'); } else { $this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below")); } } else { $form->populate($category->to_array()); } $this->view->assign('form_category', $form); $this->view->assign('category', $category); } public function deleteAction() { $id_category = $this->getRequest()->getParam('id_category'); if(empty($id_category)) { throw new Zend_Exception('Error: Category ID Missing from request'); } $table_category = new Store_Model_DbTable_Category(); $category = $table_category->get($id_category); $table_category->destroy($category); $this->_helper->FlashMessenger(array('success' => "Category was successfully deleted!")); $this->_redirect('/store-admin/category/list'); } }

Sample create view</p> <pre><code><div class="span-24"> <a href="/store-admin/category/list">List</a> <form action="<?php echo $this->form_category->getAction(); ?>" method="<?php echo $this->form_category->getMethod(); ?>"> <h2>Create a Category</h2> <p> <?php echo $this->form_category->getElement('name')->renderLabel(); ?> <br> <?php echo $this->form_category->getElement('name')->renderViewHelper(); ?> <?php echo (NULL != ($errors = $this->form_category->getElement('name')->getMessages()) ? $this->formErrors($errors) : ''); ?> </p> <p> <?php echo $this->form_category->getElement('slug')->renderLabel(); ?> <br> <?php echo $this->form_category->getElement('slug')->renderViewHelper(); ?> <?php echo (NULL != ($errors = $this->form_category->getElement('slug')->getMessages()) ? $this->formErrors($errors) : ''); ?> </p> <p> <?php echo $this->form_category->getElement('id_parent')->renderLabel(); ?> <br> <?php echo $this->form_category->getElement('id_parent')->renderViewHelper(); ?> <?php echo (NULL != ($errors = $this->form_category->getElement('id_parent')->getMessages()) ? $this->formErrors($errors) : ''); ?> </p> <p> <?php echo $this->form_category->getElement('description')->renderLabel(); ?> <br> <?php echo $this->form_category->getElement('description')->renderViewHelper(); ?> <?php echo (NULL != ($errors = $this->form_category->getElement('description')->getMessages()) ? $this->formErrors($errors) : ''); ?> </p> <p> <?php echo $this->form_category->getElement('order_by')->renderLabel(); ?> <br> <?php echo $this->form_category->getElement('order_by')->renderViewHelper(); ?> <?php echo (NULL != ($errors = $this->form_category->getElement('order_by')->getMessages()) ? $this->formErrors($errors) : ''); ?> </p> <p> <?php echo $this->form_category->getElement('submit_category')->renderViewHelper(); ?> </p> </form> </div> <script type="text/javascript"> $(document).ready( function() { $('#name').change( slugify ).keyup( slugify ); } ); function slugify() { text = $(this).val().toLowerCase(); text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); $('#slug').val(text); } </script>

Sample Category Form</p> <pre><code><?php class StoreAdmin_Form_Category extends Zend_Form { public function init() { $this->setMethod(self::METHOD_POST); $element = $this->createElement('hidden', 'id_category'); $element->removeDecorator('DtDdWrapper'); $element->removeDecorator('label'); $this->addElement($element); $element = $this->createElement('text', 'name'); $element->setLabel('Name'); $element->setRequired(TRUE); $element->removeDecorator('DtDdWrapper'); $element->setAttrib('class', 'text'); $this->addElement($element); $element = $this->createElement('text', 'slug'); $element->setLabel('Slug'); $element->setRequired(TRUE); $element->removeDecorator('DtDdWrapper'); $element->setAttrib('class', 'text'); $this->addElement($element); $element = $this->createElement('textarea', 'description'); $element->setLabel('Description'); $element->removeDecorator('DtDdWrapper'); $element->setAttrib('class', ''); $this->addElement($element); $table_category = new Store_Model_DbTable_Category(); $options = $table_category->get_tree_options(NULL, '', array(NULL => '')); $element = $this->createElement('select', 'id_parent'); $element->setLabel('Parent Category'); $element->setRequired(FALSE); $element->removeDecorator('DtDdWrapper'); $element->addMultiOptions($options); $this->addElement($element); $element = $this->createElement('text', 'order_by'); $element->setLabel('Display Order'); $element->setRequired(TRUE); $element->removeDecorator('DtDdWrapper'); $element->setAttrib('class', 'text'); $this->addElement($element); $element = $this->createElement('submit', 'submit_category'); $element->setLabel('Submit'); $element->setRequired(TRUE); $element->removeDecorator('DtDdWrapper'); $element->removeDecorator('label'); $this->addElement($element); } /** * Makes sure that a Category cannot become its own parent (causing a rescursion error) */ public function removeOption($id_category) { $this->removeElement('id_parent'); $table_category = new Store_Model_DbTable_Category(); $options = $table_category->get_tree_options(NULL, '', array(NULL => '')); if(array_key_exists($id_category, $options)) { unset($options[$id_category]); } $element = $this->createElement('select', 'id_parent'); $element->setLabel('Parent Category'); $element->setRequired(FALSE); $element->removeDecorator('DtDdWrapper'); $element->addMultiOptions($options); $this->addElement($element); } }

Zend_Form значительно упрощает контроллеры Crud.Что еще более важно, это общепринятая практика использовать их, если вы собираетесь создавать приложения на ZF.

...